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.*;
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null)
return null;
RandomListNode pNode = head, copyHead = null, copyNode = null;
Map<RandomListNode, RandomListNode> map = new HashMap<>();
while(pNode != null){
RandomListNode node = new RandomListNode(pNode.label);
node.next = null;
node.random = null;
if(pNode == head){
copyHead = copyNode = node;
}
else{
copyNode.next = node;
copyNode = copyNode.next;
}
map.put(pNode, copyNode);
pNode = pNode.next;
}
for(Map.Entry<RandomListNode, RandomListNode> m: map.entrySet()){
m.getValue().random = map.get(m.getKey().random);
}
return copyHead;
}
}