forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0138-copy-list-with-random-pointer.cs
54 lines (44 loc) · 1.2 KB
/
0138-copy-list-with-random-pointer.cs
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
47
48
49
50
51
52
53
54
/*
// Definition for a Node.
public class Node {
public int val;
public Node next;
public Node random;
public Node(int _val) {
val = _val;
next = null;
random = null;
}
}
*/
public class Solution {
public Node CopyRandomList(Node head) {
var map = new Dictionary<Node, Node>();
if (head == null) return null;
var copy = new Node(head.val);
map[head] = copy;
var cur1 = head.next;
var cur2 = copy;
// first pass to create the nodes
while(cur1 != null) {
var next2 = new Node(cur1.val);
cur2.next = next2;
//map the nodes
map[cur1] = next2;
cur1 = cur1.next;
cur2 = cur2.next;
}
cur1 = head;
cur2 = copy;
// second pass to update the random pointers
while(cur2 != null) {
var random = cur1.random != null
? map[cur1.random]
: null;
cur2.random = random;
cur1 = cur1.next;
cur2 = cur2.next;
}
return copy;
}
}