Graphic:
The process is divided into three stages, 1, which is responsible for the following node, and inserts the node into the original linked list 2, copying the random pointer of a subsequent node. 3 split the combined list into two parts.
The first part of the code:
while (currentnode!=null) {// Copy the node and insert the node behind the node Randomlistnode clonenode=New Randomlistnode (Currentnode.label); Clonenode.next=currentnode.next; Currentnode.next=clonenode; CurrentNode=clonenode.next; }
The second part of the code:
Currentnode=head; while (currentnode!=null) {// copy random pointer. randomlistnode clonenode=currentnode.next; if (currentnode.random!=null) { clonenode.random=currentnode.random.next; here to point to the back of the random pointer, because it is copied drip ah, don't forget. } currentnode=clonenode.next; }
The third part of the code:
Randomlistnode clonehead=head.next; CurrentNode=head; while (currentnode.next!=null) { Randomlistnode temp=currentnode.next; Currentnode.next=temp.next; CurrentNode=temp; }
The total code:
classRandomlistnode {intlabel; Randomlistnode Next, Random; Randomlistnode (intx) { This. Label =x;} }; Public classSolution { PublicRandomlistnode copyrandomlist (Randomlistnode head) {if(head==NULL)return NULL; Randomlistnode CurrentNode=Head; while(currentnode!=NULL){//The node is copied, and the node is inserted behind the nodeRandomlistnode clonenode=NewRandomlistnode (Currentnode.label); Clonenode.next=Currentnode.next; Currentnode.next=CloneNode; CurrentNode=Clonenode.next; } CurrentNode=Head; while(currentnode!=NULL){//copies a random pointer. Randomlistnode clonenode=Currentnode.next; if(currentnode.random!=NULL) {Clonenode.random=currentnode.random.next;//here to point to the back of the random pointer, because it is copied drip ah, don't forget. } currentnode=Clonenode.next; } Randomlistnode Clonehead=Head.next; CurrentNode=Head; while(currentnode.next!=NULL) {Randomlistnode temp=Currentnode.next; Currentnode.next=Temp.next; CurrentNode=temp; } returnClonehead; }}
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.