NOWCODER 剑指offer 复杂链表的复制

用的最直接的建立一个一个node再建立next或者random关系

运行时间:33ms

占用内存:6720k

# -*- coding:utf-8 -*-
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        # write code here
        if not pHead:
            return None
        cloneNode = RandomListNode(pHead.label)
        current = cloneNode
        while (current):
            if (pHead.next):
                cnext = RandomListNode(pHead.next.label)
                current.next = cnext
            if (pHead.random):
                crandom = RandomListNode(pHead.random.label)
                current.random = crandom
            current = current.next
            pHead = pHead.next
        return cloneNode

——————————————————————————————————————————————

标准答案很复杂

*1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;

*2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;

*3、拆分链表,将链表拆分为原链表和复制后的链表

注意拆的时候不要光想着拆一条线,这样很多结点依然粘在线上,就一个结点一个结点拆,把两条线都分开

运行时间:22ms

占用内存:5740k

# -*- coding:utf-8 -*-
# class RandomListNode:
#     def __init__(self, x):
#         self.label = x
#         self.next = None
#         self.random = None
class Solution:
    # 返回 RandomListNode
    def Clone(self, pHead):
        # write code here
        if not pHead:
            return None
        #establish next
        #a->a1->b->b1-c->c1->
        current = pHead
        while (current):
            clone = RandomListNode(current.label)
            clone.next = current.next
            current.next = clone
            current = clone.next
        #establish random
        #a->c  a1->c1
        current = pHead
        while (current):
            clone = current.next
            if (current.random):
                clone.random = current.random.next
            current = clone.next
        #splite the clone
        #a1->b1->c1  a1->c1
        cloneHead = pHead.next
        current = pHead
        while (current.next):
            cnext = current.next
            current.next = cnext.next
            current = cnext
        return cloneHead

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/82026204