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