Posts Clone Linked List with Random Pointer - Constant Space Complexity
Post
Cancel

Clone Linked List with Random Pointer - Constant Space Complexity

PROBLEM DESCRIPTION

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. Construct a deep copy of the list.

1
2
3
4
5
6
7
8
9
10
11
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

LeetCode

SOLUTION

snapshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {

    public Node copyRandomList(Node head) {

        if(head == null) return null;

        Node t = head;

        while(t != null){
            Node newNode = new Node(t.val);
            newNode.next = t.next;
            t.next=newNode;
            t=t.next.next;
        }

        t = head;

        while(t != null){
            Node r = t.random;

            if(r == null){
                t = t.next.next;
                continue;
            }

            t.next.random = r.next;
            t = t.next.next;
        }

        Node h2=head.next;
        Node t1 = head;
        Node t2 = head.next;

        while(t2 != null){
            t1.next = t2.next;
            t1 = t1.next;
            if(t1==null)break;
            t2.next = t1.next;
            t2 = t2.next;
        }

        return h2;

    }

}
This post is licensed under CC BY 4.0 by the author.