Copy List with Random Pointer
Problem
· problemA linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.
- · 0 ≤ n ≤ 1000
- · -10⁴ ≤ Node.val ≤ 10⁴
- · Node.random is null or points to some node in the linked list
Pre-solve
· pre-solve- ☐Do we need to handle an empty list (head = None)?
- ☐Can a node's random pointer point to itself?
- ☐Can a node's random pointer be null?
- ☐Can new_node pointers point to original nodes?
- ☐Can we modify the original list?
- ☐Can we solve this with less than O(n) space?
- ☐Can we use a different data structure instead of a hash map?
Logic Structure
· logicoldToCopy = {None: None}oldToCopy = {}oldToCopy = {head: None}while cur:
while cur.next:
while cur is not None:
copy = Node(cur.val)
copy = Node(cur)
copy = cur
oldToCopy[cur] = copy
oldToCopy[copy] = cur
oldToCopy[cur.val] = copy
while cur:
while cur.next:
while cur:
copy.next = oldToCopy[cur.next]
copy.next = cur.next
copy.next = oldToCopy.get(cur.next)
copy.random = oldToCopy[cur.random]
copy.random = cur.random
copy.random = oldToCopy[cur].random
Solve · Trace
· solve[[7,null],[13,0],[11,4],[10,2],[1,0]]→
[[7,null],[13,0],[11,4],[10,2],[1,0]]
[[1,1],[2,1]]→
[[1,1],[2,1]]
[[3,null],[3,0],[3,null]]→
[[3,null],[3,0],[3,null]]