# Definition for singly-linked list with a random pointer.# class RandomListNode:# def __init__(self, x):# self.label = x# self.next = None# self.random = NoneclassSolution:# @param head: A RandomListNode# @return: A RandomListNodedefcopyRandomList(self,head):# write your code here# Deep copy: coppy the whole list and connect all node togetherifhead==None:returnhead# hash_map: {node_in_old_list, node_in_new_lsit}hash_map={}dummy=RandomListNode(0)cur=dummywhilehead!=None:# check if head in the hash_mapifhash_map.has_key(head):new_node=hash_map[head]else:# create new onenew_node=RandomListNode(head.label)hash_map[head]=new_node# new_node.next will be connected by the following line.cur.next=new_node# need to fix the new_node.randomifhead.random!=None:ifhash_map.has_key(head.random):new_node.random=hash_map[head.random]else:new_random_node=RandomListNode(head.random.label)new_node.random=new_random_nodehash_map[head.random]=new_random_nodecur=cur.nexthead=head.nextreturndummy.next
For the Space O(1) solution, you should firstly create all nodes and new_nodes.random = old_nodes.random. After that, you update the new_nodes.random