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.
Difficulty: Hard
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
if(head == null) return null;
RandomListNode newHead = new RandomListNode(head.label);
RandomListNode oldList = head;
RandomListNode newList = newHead;
while(oldList != null){
if(oldList.next != null){
newList.next = new RandomListNode(oldList.next.label);
}
else{
newList.next = null;
}
map.put(oldList, newList);
oldList = oldList.next;
newList = newList.next;
}
oldList = head;
newList = newHead;
while(oldList != null){
if(oldList.random == null){
newList.random = null;
}
else{
newList.random = map.get(oldList.random);
}
oldList = oldList.next;
newList = newList.next;
}
return newHead;
}
}