Copy List with Random Pointer
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;
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode dummy = new RandomListNode(-1);
RandomListNode cursor = dummy;
RandomListNode p = head;
while (p != null) {
RandomListNode node = new RandomListNode(p.label);
cursor.next = node;
cursor = node;
map.put(p, node);
p = p.next;
}
p = head;
while (p != null) {
map.get(p).random = map.get(p.random);
p = p.next;
}
return map.get(head);
}