-
Notifications
You must be signed in to change notification settings - Fork 3
/
138.cpp
37 lines (35 loc) · 779 Bytes
/
138.cpp
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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*, Node*> old2new;
Node* sentinel = new Node(-1);
Node* curr = sentinel;
while (head) {
curr->next = new Node(head->val);
curr = curr->next;
old2new[head] = curr;
curr->random = head->random;
head = head->next;
}
curr = sentinel->next;
while (curr) {
curr->random = old2new[curr->random];
curr = curr->next;
}
return sentinel->next;
}
};