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.
Solution:
Copy the list within the original list
original: A→B→C
after: A→A’→B→B’→C→C’
Copy the random pointer. Notice need to check if it’s None
""" # 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 """
classSolution: defcopyRandomList(self, head: 'Node') -> 'Node': ifnot head: return head p = head while p: newNode = Node(p.val) newNode.next = p.next p.next = newNode p = p.next.next p = head while p: if p.random: p.next.random = p.random.next p = p.next.next copy, p = head.next, head.next while p.next: head.next = p.next head = head.next p.next = head.next p = p.next head.next = None return copy