Original title Address
A very ingenious approach that does not require a map and requires only O (1) of additional storage space, divided into 3 steps:
1. Copy the linked list first, but this replication is special, each newly-replicated node is added to the back of the original node, which is equivalent to the "stopper"
2. Construct the random pointer of the new node based on the Ramdon pointer of the original node
3. Restore the original linked list structure while getting a new copy of the linked list
Time complexity: O (N)
Note that the random may be null
Code:
1Randomlistnode *copyrandomlist (Randomlistnode *head) {2Randomlistnode *h =NULL;3 4h =head;5 while(h) {6Randomlistnode *node =NewRandomlistnode (h->label);7Node->next = h->Next;8H->next =node;9H = h->next->Next;Ten } One Ah =head; - while(h) { -H->next->random = H->random? H->random->Next:null; theH = h->next->Next; - } - -h = head? Head->Next:null; + while(head) { -Randomlistnode *tmp = head->Next; +Head->next = head->next->Next; ATmp->next = Head->next? Head->next->Next:null; atHead = head->Next; - } - - returnh; -}
leetcode#138 Copy List with Random Pointer