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.
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
import java.util.HashMap;
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
RandomListNode dummy = new RandomListNode(0);
RandomListNode previous = dummy, current;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
while(head != null){
if(map.containsKey(head)){
current = map.get(head);
} else {
current = new RandomListNode(head.label);
map.put(head, current);
}
previous.next = current;
if(head.random != null){
if(map.containsKey(head.random)){
current.random = map.get(head.random);
} else {
current.random = new RandomListNode(head.random.label);
map.put(head.random, current.random);
}
}
previous = current;
head = head.next;
}
return dummy.next;
}
}