A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.
Return a deep copy of the list.
General Solution:
You must first iterate over the copy single linked list. Each node that builds a 1-to-1 map,copy during traversal is the value of the pair with the previous node key. This allows you to assign random values to the second iteration.
PublicRandomlistnode copyrandomlist (Randomlistnode head) {if(Head = =NULL)return NULL; Randomlistnode NextNode=NULL; varSentinel =NewRandomlistnode (-1); Sentinel.next=Head; varSentinel2 =NewRandomlistnode (-1); vardummy =Sentinel2; varHashtable =NewDictionary<randomlistnode,randomlistnode>(); //copy; while(Head! =NULL) { varNewcopy =NewRandomlistnode (Head.label); Hashtable. ADD (head,newcopy); Sentinel2.next=newcopy; Head=Head.next; Sentinel2=Sentinel2.next; } //copy Random varNewhead =Sentinel.next; varNewlisthead =Dummy.next; while(Newhead! =NULL) { varRandom =Newhead.random; Newlisthead.random= (random==NULL)?NULL: Hashtable[random]; Newhead=Newhead.next; Newlisthead=Newlisthead.next; } returnDummy.next; }
There are great gods http://fisherlei.blogspot.com/2013/11/leetcode-copy-list-with-random-pointer.html on the internet to give a very ingenious method.
PublicRandomlistnode copyrandomlist (Randomlistnode head) {if(Head = =NULL)return NULL; Randomlistnode NextNode=NULL; varSentinel =NewRandomlistnode (-1); Sentinel.next=Head; //copy; while(Head! =NULL) { varNewcopy =NewRandomlistnode (Head.label); NextNode=Head.next; Head.next=newcopy; Newcopy.next=NextNode; Head=NextNode; } //copy Random varNewhead =Sentinel.next; while(Newhead! =NULL) { varRandom =Newhead.random; varFollow =Newhead.next; Follow.random= (random==NULL)?NULL: Random.next; Newhead=Follow.next; } //split into 2 lists varLegacy =Sentinel.next; varPilot =NewRandomlistnode (-1); vardummy =pilot; while(Legacy! =NULL) {Pilot.next=Legacy.next; Pilot=Pilot.next; Legacy.next=Legacy.next.next; Legacy=Legacy.next; } returnDummy.next; }
138. Copy List with Random Pointer