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.
Analysis:
The key to this question is actually how to copy the random pointer, find a random pointer point to node, time complexity is O (n). Therefore the total complexity is in O (n^2).
Here is a more ingenious method. Add a node behind each node, and the new node has the same value as the previous node. In this case, the random pointer is easy to copy,
1 /**2 * Definition for singly-linked list with a random pointer.3 * Class Randomlistnode {4 * int label;5 * Randomlistnode Next, random;6 * Randomlistnode (int x) {This.label = x;}7 * };8 */9 Public classSolution {Ten /** One * @param head:the head of linked list with a random pointer. A * @return: A new head of a deep copy of the list. - */ - Publicrandomlistnode copyrandomlist (Randomlistnode listhead) { the if(Listhead = =NULL)returnListhead; -Randomlistnode current =Listhead; - //Add Duplicate Nodes - while(Current! =NULL) { +Randomlistnode node =NewRandomlistnode (Current.label); -Node.next =Current.next; +Current.next =node; ACurrent =Current.next.next; at } - - //set random pointer -Current =Listhead; - while(Current! =NULL) { - if(Current.random! =NULL) { inCurrent.next.random =Current.random.next; - } toCurrent =Current.next.next; + } - the //Restore and Detach *Randomlistnode Newhead =Listhead.next; $Randomlistnode current1 =Listhead;Panax NotoginsengRandomlistnode Current2 =Newhead; - while(Current1! =NULL) { theCurrent1.next =Current2.next; +Current1 =Current1.next;if (current1! = null) {//Very important, cannot remove it.42 Current2.next = current 1.NEXT;43} -Current2 =Current2.next; $ } $ returnNewhead; - } -}
Reprint Please specify source: cnblogs.com/beiyeqingteng/
Copy List with Random Pointer