/**138. Copy list with Random pointer * @param head * @return deep copy of a linked list, using the reallocation memory to save the new */Public Randomlistnode Co
Pyrandomlist (Randomlistnode head) {if (head = = NULL | | head.next = NULL) {return head;
} map<randomlistnode, randomlistnode> Map = new Hashmap<randomlistnode, randomlistnode> ();
Randomlistnode ret = new Randomlistnode (Head.label);
Map.put (head, ret);
Randomlistnode rhead = ret;
Randomlistnode phead = head;
while (head!= null) {randomlistnode node = new Randomlistnode (Head.label);
Map.put (head, node);
Ret.next = node;
ret = Ret.next;
head = Head.next;
ret = Rhead;
head = Phead;
while (head!= null) {ret.random = Map.get (head.random);
ret = Ret.next;
head = Head.next;
return rhead; }
The /*hashmap key is stored in the original Pointer,value the new pointer. First time, do not copy the value of random, only copy values to create a new linked list.
And the new and old pointer exist in HashMap. The second time, iterate over the old table, copy the value of random, because the first time has already copied the list and also exists in the HashMap, so just from the HashMap,
The current old node.random is used as a key value, and the value of the new values is obtained and assigned to the new node.random. * */
Public Randomlistnode CopyRandomList1 (Randomlistnode head) {if (head = = null) return head;
/* First step: After each node in the oldlist insert a copynode (copy linked list node)/Randomlistnode Nownode = head;
while (Nownode!= null) {Randomlistnode Copynode = new Randomlistnode (Nownode.label);
Copynode.random = Nownode.random;
Copynode.next = Nownode.next;
Nownode.next = Copynode;
Nownode = NowNode.next.next; }/* Step two: Determine each node of the NewList, which is really associated with the random node, * Because the first step has been established on all newlist nodes/Nownode = Head
; while (Nownode!= null) {if (nownode.random!= null) {nowNode.next.random = Nownode.random
. Next;
} Nownode = NowNode.next.next; }/* Step three: Restore Oldlist next as a starting next node * and Splice newlist next to the next node it really should be associated with * that is, keep the old list oldl
ist unchanged, splicing new linked list newlist. * */
Randomlistnode phead = new Randomlistnode (0);
Phead.next = head;
Randomlistnode newlist = Phead;
Nownode = head;
while (Nownode!= null) {phead.next = Nownode.next;
Nownode.next = PHead.next.next;
Phead = Phead.next;
Nownode = Nownode.next;
return newlist.next; }