Construct a deep copy of the list.
The linked list is represented in the input/output as a list of n
nodes. Each node is represented as a pair of [val, random_index]
where:
val
: an integer representing Node.val
random_index
: the index of the node (range from 0
to n-1
) that the random
pointer points to, or null
if it does not point to any node.Your code will only be given the head
of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
解法一: 建一个dict,先对每个点copy一个点存在dict的值里,再对每个dict的值,把next和random加上去。 注意:dic[i]如果没有值就会报错,所以这里用dic.get(i),防止有的点random是空,或者最后一个点next是空。 time: O(2n) space: O(n)
""" # 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]': dic = {} node = cur = head while node: dic[node] = Node(node.val) node = node.next while cur: dic[cur].next = dic.get(cur.next) dic[cur].random = dic.get(cur.random) cur = cur.next return dic.get(head)