Innovation Workshop Pen question copy List with Random Pointer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.