copy list with random pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

分析

直接遍历链表,遇到需要的就创建或者返回,用MAP记录NODE: old node: new node

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""


class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        if not head:
            return
        map = {}
        def getnode(cur):
            if cur not in map:
                map[cur] = Node(cur.val)
            return map[cur]
            
        cur = head
        while cur:
            node = getnode(cur)
            if cur.next:
                node.next = getnode(cur.next)
            if cur.random:
                node.random = getnode(cur.random)
            cur = cur.next
        return getnode(head)

2个loop,第一个复制新Node插入旧node后面。第二次设置新建Node们的random指针。最后split2个链表

可以用Map,就是耗空间。用原地copy省空间 No extra space

这里cur=head,用cur走

最后split,cur=dummy=nhead

最后split用cur.next.next一直出错 以后尽量不用.next.next

Last updated

Was this helpful?