[Leedcode 138] Copy List with Random Pointer

Source: Internet
Author: User

A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.

Return a deep copy of the list.

/*** Definition for singly-linked list with a random pointer. * Class Randomlistnode {* int label; * Randomlist Node Next, Random; * Randomlistnode (int x) {This.label = x;}}; */ Public classSolution { PublicRandomlistnode copyrandomlist (Randomlistnode head) {//The sword refers to the offer26 problem, p147        if(head==NULL)return NULL; Randomlistnode cur=Head;  while(cur!=NULL){//The first step is to copy Node n ', which is placed behind the original node nRandomlistnode newnode=NewRandomlistnode (Cur.label); Newnode.next=Cur.next; Cur.next=NewNode; Cur=Newnode.next; } cur=Head;  while(cur!=NULL){//second step, copy the random pointer            if(cur.random!=NULL) {Cur.next.random=Cur.random.next; } cur=Cur.next.next; } cur=head;//The third step is to split the long list into two linked lists, and pay attention to the processing method of the tail node.Randomlistnode res=Head.next; Randomlistnode Pnode=Res;  while(cur!=NULL) {Cur.next=Cur.next.next; Cur=Cur.next; if(pnode.next!=NULL)////Tail Nodepnode.next=Pnode.next.next; Pnode=Pnode.next; }        returnRes; }}

[Leedcode 138] 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.