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.
/*** Definition for singly-linked list with a random pointer. * Class Randomlistnode {* int label; * Randomlist Node Next, Random; * Randomlistnode (int x) {This.label = x;}}; */ Public classSolution { PublicRandomlistnode copyrandomlist (Randomlistnode head) {//The sword refers to the offer26 problem, p147 if(head==NULL)return NULL; Randomlistnode cur=Head; while(cur!=NULL){//The first step is to copy Node n ', which is placed behind the original node nRandomlistnode newnode=NewRandomlistnode (Cur.label); Newnode.next=Cur.next; Cur.next=NewNode; Cur=Newnode.next; } cur=Head; while(cur!=NULL){//second step, copy the random pointer if(cur.random!=NULL) {Cur.next.random=Cur.random.next; } cur=Cur.next.next; } cur=head;//The third step is to split the long list into two linked lists, and pay attention to the processing method of the tail node.Randomlistnode res=Head.next; Randomlistnode Pnode=Res; while(cur!=NULL) {Cur.next=Cur.next.next; Cur=Cur.next; if(pnode.next!=NULL)////Tail Nodepnode.next=Pnode.next.next; Pnode=Pnode.next; } returnRes; }}
[Leedcode 138] Copy List with Random Pointer