Did not understand the purpose of the topic, read the online solution. The main problem is that we usually replicate one node at a time, but for random nodes it is possible to replicate, that node has not yet been created!! So how do you copy the point of a disorderly order??
The brute force solution is to create all the nodes first, and then each node's random point loops through the list until it finds the node that the order points to, making a copy connection!!! Time complexity is very high!!
The classic practice is to first loop in each node after the insertion of a replicated node, the second loop can be the corresponding chaos point to the replication connection to the newly created node (definitely in the original node after the node), the third cycle can be separated by the new node in sequence!
1 /**2 * Definition for singly-linked list with a random pointer.3 * struct Randomlistnode {4 * int label;5 * Randomlistnode *next, *random;6 * Randomlistnode (int x): label (x), Next (null), random (null) {}7 * };8 */9 classSolution {Ten Public: OneRandomlistnode *copyrandomlist (Randomlistnode *head) { A if(Head==null)returnhead; -Randomlistnode *p; -p=head; the while(P) - { -Randomlistnode *copy=NewRandomlistnode (p->label); -Copy->next=p->Next; +p->next=copy; - +P=p->next->Next; A } atp=head; - while(P) - { - if(p->random==null) p->next->random=NULL; - ElseP->next->random=p->random->Next; -P=p->next->Next; in } -Randomlistnode node (0); to //node.next=head->next; +p=&node; - while(head) the { *P->next=head->Next; $Head->next=head->next->Next;Panax NotoginsengHead=head->Next; -P=p->Next; the + } A returnNode.next; the } +};
Copy List with Random Pointer