title :
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.
Code : runtime:215 ms
1 #Definition for singly-linked list with a random pointer.2 #class Randomlistnode:3 #def __init__ (self, x):4 #Self.label = x5 #Self.next = None6 #self.random = None7 8 classSolution:9 #@param head, a randomlistnodeTen #@return a Randomlistnode One defcopyrandomlist (Self, head): A ifHead isNone: - returnHead - the #Insert newnode between every, nodes between Oldlist -p =Head - whileP is notNone: -NewNode =Randomlistnode (P.label) +TMP =P.next -P.next =NewNode +Newnode.next =tmp Ap =tmp at - #copy Random Point -p =Head - whileP is notNone: - ifP.random is notNone: -P.next.random =P.random.next inp =P.next.next - to #extract the new list from mixed list +Newhead =Head.next -p =Head the whileP is notNone: *TMP =P.next $P.next =P.next.nextPanax Notoginsengp =P.next - ifTmp.next: theTmp.next =Tmp.next.next +TMP =Tmp.next A the returnNewhead
Ideas :
I can not think of a clever way to find a reliable online post:
http://mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5ODIzNDQ3Mw==&appmsgid=10000291&itemidx=1&sign= ccde63918a24dee181f1fd1a4e3e6781
The Python code is written with the idea of the above post.
One problem is that "if Head.next is None:return head" when judging extreme cases at first
Results have been error, and then removed after the AC. Pay attention to a point when you want to copy it.
There is, has been the python inside the variable assignment is not very clear, Google has a log below, speaking more reliable.
Http://www.cnblogs.com/evening/archive/2012/04/11/2442788.html
Leetcode "Copy List with Random Pointer" Python implementation