Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Copy List with Random Pointer #49

Open
kokocan12 opened this issue Jul 1, 2022 · 0 comments
Open

Copy List with Random Pointer #49

kokocan12 opened this issue Jul 1, 2022 · 0 comments

Comments

@kokocan12
Copy link
Owner

kokocan12 commented Jul 1, 2022

Problem

When a root node of Linked List is given, each node has next, random pointer,
deep copy the original Linked List.

None of the deep copied elements points the element of original Linked List.

Approach

Using object dictionary, store matching information of Linked List.
For example, key: Node -> value: Node.
After storing to dictionary, Node.random = dict.get(Node.random).

The code is below.

const copyRandomList = function(head) {
    const dict = new WeakMap();
    const headTemp = head;
    const dummy = new Node(0);
    let current = dummy;
    
    while(head) {
        current.next = new Node(head.val);
        dict.set(head, current.next)
        
        current = current.next;
        head = head.next;
    }
    
    head = headTemp;
    current = dummy.next;
    while(head) {
        current.random = dict.get(head.random);
        
        current = current.next;
        head = head.next;
    }
    
    return dummy.next;
};
# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant