Q12 Copy List with Random Pointer - LeetCode 1st approach

PHOTO EMBED

Mon Jan 16 2023 18:35:24 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

/*
// 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;
    }
}


















content_copyCOPY

https://leetcode.com/problems/copy-list-with-random-pointer/