Copy List with Random Pointer

Source: Internet
Author: User

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

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.