https://leetcode.com/problems/copy-list-with-random-pointer/
Copy List with Random Pointer
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.
Title: Known linked list, it has additional random pointer information, the random pointer can point to any node or null, copy the linked list.
In three steps: 1. Copy the node after each node 2. Copy the random pointer 3. Separate the old and new lists to get the copy list
Reference http://www.cnblogs.com/zuoyuan/p/3745126.html well written, very clear.
Note: After considering "21 lines" Why is the If tmp.random, the topic is known that this random pointer can be either node or NULL, this is not to put null this situation is not considered.
In fact, it's test instructions. Understanding error: Each node holds a value, and this value (information) is a pointer to another node or null.
Tmp.random is a value, it cannot be empty, you can save the information pointing to NULL, there is no contradiction.
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==none:returnNone -tmp=Head - whileTmp:#copy an identical node after each node in the original list and connect theNewnode=randomlistnode (Tmp.label)#with NewNode, convenient to the back of the transmission -newnode.next=Tmp.next -tmp.next=NewNode -tmp=Tmp.next.next +Tmp=head#Reset the TMP pointer back to the head, just like the i=0, and re-assign the initial value - whileTmp:#omission of this item + ifTmp.random:#The next (that is, the copy node) of its node in the original list, how does it copy the random pointer? ATmp.next.random=tmp.random.next#The next (that is, its copy node), which is the random point of the original node, is exactly the same point, which implements the copy of the random pointer. attmp=Tmp.next.next -Newhead=Head.next -p1=Head -P2=Newhead - whileP2.next:#split the original linked list from the copy list -p1.next=P2.next inp1=P1.next -P2.next=p1.next#carelessness omitted the next of P2.next . toP2=P2.next +P1.next=none#The end of the order to none, to ensure the correctness of the original list (previously separated p1.next there is a copy item, delete with none) -p2.next=None the returnNewhead#Newhead is the copy linked list that is established via the pointer P2
Copy List with Random Pointer