A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null)
return null;
RandomListNode nhead = new RandomListNode(head.label);
RandomListNode optr = head;
RandomListNode nptr = nhead;
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
map.put(optr, nptr);
nptr.random = optr.random;
optr = optr.next;
while (optr != null) {
RandomListNode tmp = new RandomListNode(optr.label);
nptr.next = tmp;
nptr = tmp;
nptr.random = optr.random;
map.put(optr, nptr);
optr = optr.next;
}
nptr.next = null;
nptr = nhead;
while (nptr != null) {
if (nptr.random != null) {
nptr.random = map.get(nptr.random);
}
nptr = nptr.next;
}
return nhead;
}