-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path138.cpp
More file actions
executable file
·24 lines (24 loc) · 759 Bytes
/
138.cpp
File metadata and controls
executable file
·24 lines (24 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
Node *res = new Node(head->val, nullptr, nullptr);
Node *copy_node = res, *original = head->next;
unordered_map<Node*, Node*> m;
m[head] = res;
while (original) {
Node *t = new Node(original->val, nullptr, nullptr);
copy_node->next = t;
m[original] = t;
copy_node = copy_node->next;
original = original->next;
}
copy_node = res; original = head;
while (original) {
copy_node->random = m[original->random];
copy_node = copy_node->next;
original = original->next;
}
return res;
}
};