Original title address: https://oj.leetcode.com/problems/copy-list-with-random-pointer/
Test instructions
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.
Problem solving idea: This problem is mainly need deep copy. Look at the picture to understand how to write the program.
The first step is to insert a new node after each node in the original list, and the new node will have the same content as the previous node. For example, insert 2 after 1 after inserting, and so on.
In the second step, how does the random pointer in the original list map? For example, the 1-node random pointer points to 3, and the 4-node random pointer points to 2. If there is a TMP pointer pointing to 1 (blue), then one statement: Tmp.next.random = tmp.random.next; This problem can be solved.
The third step is to split the new linked list from such a list.
Code:
#Definition for singly-linked list with a random pointer.#class Randomlistnode:#def __init__ (self, x):#Self.label = x#Self.next = None#self.random = NoneclassSolution:#@param head, a randomlistnode #@return a Randomlistnode defcopyrandomlist (Self, head):#http://www.cnblogs.com/zuoyuan/p/3745126.html ifHead = = None:returnNone#Step 1:duplicate nodes in orderTMP =Head whileTmp:newnode=Randomlistnode (Tmp.label) Newnode.next=Tmp.next Tmp.next=NewNode tmp=Tmp.next.next#Step 2:preseve Random pointerTMP =Head whiletmp:ifTmp.random:tmp.next.random= Tmp.random.next#assign the old node's random pointer to new duplicated node ' s random filedTMP =Tmp.next.next#Step 3:extract New list and returnNewhead =Head.next Pold=Head pnew=Newhead whilePnew.next:pold.next=Pnew.next Pold=Pold.next Pnew.next=Pold.next pnew=Pnew.next Pold.next=None Pnew.next=NonereturnNewhead
Reference:
Http://www.cnblogs.com/zuoyuan/p/3745126.html
[Leetcode] Copy List with Random Pointer @ Python