Let's say it's the next linked list:
123456 |
struct Node
{
    
int
value;
    
struct Node *next;
    
struct Node *random;
}
|
where random points to any node of the linked list or null, program the deep copy of the linked list to be implemented.
1 |
Node *deepCopy (Node *head)
|
Parse: Insert the new node behind the corresponding old node:
In two steps
1. Building a new node random pointer: New1->random = old1->random->next, new2-random = null, New3-random = null, New4->random = old 4->random->next
2. Restore the original linked list and build a new linked list: for example old1->next = old1->next->next, New1->next = New1->next->next
The algorithm time complexity O (N), Spatial complexity O (1)
Code:
Node *deepcopy (node *head) { node* now = head; node* next = head->next; while (now = NULL) { node * copy = new Node; Copy->value = now->value; Copy->next = now->next; Now->next = copy; Now = Next; Next = next->next; } now = head; while (now = NULL) { now->next->random = now->random->next; now = now->next->next; } node* head2 = head->next; node* Newhead = head->next; while (head2->next! = NULL) { Head->next = head2->next; Head2->next = head2->next->next; Head = head->next; head2 = head2->next; } return newhead;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Innovation Workshop Pen question copy List with Random Pointer