/* // Definition for a Node. class Node { int val; Node next; Node random; public Node(int val) { this.val = val; this.next = null; this.random = null; } } */ class Solution { public Node copyRandomList(Node head) { Node nh = null; Node curr = head; Node copy = nh; //HM to copy map new orignal to new node addresses HashMap<Node,Node> map = new HashMap<>(); //making deep copy of LL while(curr!=null){ if(nh == null){ //for first node nh = new Node(curr.val); copy = nh; } else{ //for rest of the nodes Node temp = new Node(curr.val); copy.next = temp; copy = copy.next; } map.put(curr , copy); //mapping curr = curr.next; } map.put(null , null); //to handle cases where random node is pointing to null curr = head; copy = nh; //setting random nodes of the new LL while(curr != null){ copy.random = map.get(curr.random) ; curr = curr.next; copy = copy.next; } return nh; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter