Joey LIU | NANTSOU


 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
/*
// 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;
        
        Map<Node, Node> map = new HashMap<>();
        Node res = new Node(-1);
        Node copy = res;
        
        while (head != null) {
            if (map.containsKey(head)) {
                copy.next = map.get(head);
            } else {
                copy.next = new Node(head.val);
                map.put(head, copy.next);
            }
            
            if (head.random != null) {
                if (map.containsKey(head.random)) {
                    copy.next.random = map.get(head.random);
                } else {
                    copy.next.random = new Node(head.random.val);
                    map.put(head.random, copy.next.random);
                }
            }
            copy = copy.next;
            head = head.next;
        }
        return res.next;
    }
}