# Simple Java Solution

• Deep copying a linked list is fairly simple. Just loop through and create a node based on the original list node. But in this problem, it became tricky due to the random nodes. The random nodes might point to a node which is already copied or it might point to a node which will be created later. To overcome this, I have used a map that contains all the nodes. Checked that map before creating any node. If node is already created due to random node, used the existing one.

``````/**
* 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 {
return null;
}

Map<RandomListNode, RandomListNode> nodes = new HashMap<>();
RandomListNode prevNewNode = null;

while(curNode != null) {
RandomListNode newNode = nodes.get(curNode); //check if already exists.
if(newNode == null) {
newNode = new RandomListNode(curNode.label);
nodes.put(curNode, newNode);
}

//set random
if(curNode.random != null) {
RandomListNode randomNode = nodes.get(curNode.random); // check if the random node already created.
if(randomNode == null) {
randomNode = new RandomListNode(curNode.random.label);
nodes.put(curNode.random, randomNode);
}
newNode.random = randomNode;
}

//set next
} else {
prevNewNode.next = newNode;
}
prevNewNode = newNode;
curNode = curNode.next;

}