Python solves complex linked list replication

Source: Internet
Author: User

The topics are as follows: Enter a complex list of nodes with node values in each node, and two pointers, one pointing to the next node, and another with a special pointer to any node, returning the result to the head of the complex linked list after replication. (Note that in the output, do not return the node reference in the parameter, otherwise the program will return null directly)

Idea: The first step is to replicate the nodes on the basis of the original linked list, copying the nodes behind the original nodes. The second step replicates the random nodes. The third step separates the old and new linked lists. The diagram is as follows

The code is as follows:

#Encoding:utf8classRandomlistnode ():def __init__(self,x): Self.label=x Self.next=None self.random=NoneclassSolution:defClone (phead):ifPhead = =None:returnNone#replication nodes after the original nodePcur =Phead while(Pcur! =None): node=Randomlistnode (Pcur.label) Node.next=Pcur.next Pcur.next=node Pcur=Node.next#Copy the random nodePcur =Phead while(Pcur! =None):ifPcur.random! =None:pCur.next.random=PCur.random.next pcur=PCur.next.next Head=Phead.next cur=Head#detach the old and new linked listPcur =Phead while(Pcur! =None): Pcur.next=PCur.next.nextifCur.next! =None:cur.next=Cur.next.next cur=Cur.next pcur=Pcur.nextreturnHead

Python solves complex linked list replication

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.