Replication of complex linked lists

Source: Internet
Author: User

Enter a complex list with node values in each node, and two pointers, one pointing to the next node, and the other a special pointer to any node.

A clever solution is this: copy next as it turns out to be a->b->c into A->a '->b->b '->c->c ', and then navigate through the previous random pointer after a random pointer, Then split into two linked lists. Both time complexity and spatial complexity are O (n).

Implementation code:

/*Public class Randomlistnode {int label;    Randomlistnode next = null;    Randomlistnode random = null;    Randomlistnode (int label) {this.label = label; }}*/ Public classSolution { Publicrandomlistnode Clone (Randomlistnode phead) {if(phead==NULL)            return NULL; Randomlistnode Curnode=Phead;  while(Curnode! =NULL) {randomlistnode node=NewRandomlistnode (Curnode.label); Node.next=Curnode.next; Curnode.next=node; Curnode=Node.next; } Curnode=Phead;  while(Curnode! =NULL) {            if(Curnode.random! =NULL) {CurNode.next.random=CurNode.random.next; } Curnode=CurNode.next.next; } Curnode=Phead; Randomlistnode Curclonedhead=NULL; Randomlistnode Curclonednode=NULL; if(Curnode! =NULL) {Curclonedhead= Curclonednode =Curnode.next; Curnode.next=Curclonednode.next; Curnode=Curnode.next; }         while(Curnode! =NULL) {Curclonednode.next=Curnode.next; Curclonednode=Curclonednode.next; Curnode.next=Curclonednode.next; Curnode=Curnode.next; }        returnCurclonedhead; }        }

Replication of complex lists

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.