A linked list is given such that each node contains an additional random pointer which cocould point to any node in the list or null.
Return a deep copy of the list.
/** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int label; * RandomListNode next, random; * RandomListNode(int x) { this.label = x; } * }; */
Question]
A deep copy of a linked list. In addition to the next pointer, the linked list also contains a random pointer that points to a node in the string or is empty.
[Idea 1] (from the Network)
Assume that the original linked list is as follows, the thin line indicates the next pointer, the crude line indicates the random pointer, and all undrawn pointers point to NULL:
When creating a new node, the pointer changes as follows, that is, the new node is inserted after the corresponding old node:
[Java code]
Public class solution {public randomlistnode copyrandomlist (randomlistnode head) {If (Head = NULL) return NULL; // the first scan: copy each node, insert the copied new node into the original node and then randomlistnode node = head; while (node! = NULL) {randomlistnode newnode = new randomlistnode (node. label); newnode. next = node. next; node. next = newnode; node = newnode. next;} // scan the second time: Assign node = head to the random of the new node based on the random of the original node; while (node! = NULL) {If (node. Random! = NULL) node. next. random = node. random. next; node = node. next. next;} randomlistnode newhead = head. next; // scan for the third time: Split the new node from the original linked list node = head; while (node! = NULL) {randomlistnode newnode = node. Next; node. Next = newnode. Next; If (newnode. Next! = NULL) newnode. Next = newnode. Next. Next; node = node. Next;} return newhead ;}}
[Reference]
Http://www.cnblogs.com/TenosDoIt/p/3387000.html
Http://blog.csdn.net/linhuanmars/article/details/22463599
[Leetcode] Copy list with random pointer solution report