Title: A Linked list is given such, each node contains an additional random pointer which ist or null. Return a deep copy of the list.
Just finished reading the topic is to return a list with a random pointer copy. In fact, still not quite understand the meaning of the topic. So read the answer directly, after reading, I probably understand what it means. is to return a list that is exactly the same as the original one. The knot idea is as follows:
After each node in the original list, insert a replication node, that is, first of all the nodes in the original list copied side;
The value of the random domain of these replicated nodes is adjusted to point to the replicated nodes of the corresponding nodes of the original linked list;
Adjusts the value of the next field for all replicated nodes and restores the next value of all nodes in the original list to the initial state.
This is clear, the code is divided into three cycles to complete the above three goals, this method defeated more than 70% users. Code in:
public static Randomlistnode CopyRandomList1 (Randomlistnode head) {Randomlistnode iter = head, next;
Round:make copy of each node,//and link them together side-by-side into a single list.
while (ITER!= null) {next = Iter.next;
Randomlistnode copy = new Randomlistnode (Iter.label);
Iter.next = copy;
Copy.next = Next;
iter = next;
}//Second round:assign random pointers for the copy nodes.
iter = head;
while (ITER!= null) {if (iter.random!= null) {iter.next.random = Iter.random.next;
iter = Iter.next.next;
}//Third Round:restore the original list, and extract the copy list.
iter = head;
Randomlistnode pseudohead = new Randomlistnode (0);
Randomlistnode copy, copyiter = Pseudohead; while (ITER!= null) {next = Iter.next.next;
Extract the copy copy = Iter.next;
Copyiter.next = copy;
Copyiter = copy;
Restore the original list iter.next = next;
iter = next;
return pseudohead.next; }