Q-12 Copy List with Random Pointer - LeetCode 2nd approach

PHOTO EMBED

Mon Jan 16 2023 18:43:12 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) {
        if(head == null ) return null;
        Node curr = head;

        while(curr != null){
            Node forward = curr.next;

            Node temp = new Node(curr.val);
            curr.next = temp;
            temp.next = forward;

            curr = forward;
        }
        curr = head;
        Node nh = head.next;

        //copying random pointers
        while(curr != null){
            Node random = curr.random;

            if(random!=null)
                curr.next.random = random.next;

                curr = curr.next.next;
        }

        //organizing the linkedLists

        Node dummy = new Node(-1);
        curr = head;

        while(curr != null){
            dummy.next = curr.next;
            curr.next = curr.next.next;

            dummy = dummy.next;
            curr = curr.next;
        }
        return nh;
    }
}








content_copyCOPY

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