LeetCode link: https://leetcode.com/problems/copy-list-with-random-pointer/
Question Description:
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.
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) where random pointer points to, or null if it does not point to any node.
Method:
- Create hash table, copy every node to hash table.
- Build relationship according to original linked list.
Code:
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
return None
nodeDict = dict()
# First loop to copy all node
pointer = head
while pointer:
nodeDict[pointer] = Node(pointer.val, None, None)
pointer = pointer.next
# Second loop to copy relationship
pointer = head
while pointer:
if pointer.next:
nodeDict[pointer].next = nodeDict[pointer.next]
if pointer.random:
nodeDict[pointer].random = nodeDict[pointer.random]
pointer = pointer.next
return nodeDict[head]