-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq_138_copy_list_w_random_pointer.cpp
More file actions
49 lines (45 loc) · 1.1 KB
/
q_138_copy_list_w_random_pointer.cpp
File metadata and controls
49 lines (45 loc) · 1.1 KB
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
/*
// 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) {
auto i = head;
Node* new_list_head = nullptr;
auto j = new_list_head;
unordered_map<Node *, Node *> old_to_new;
while (i != nullptr) {
auto p = new Node(i->val);
old_to_new.insert(pair<Node *, Node *>(i, p));
// cout << "p->val=" << p->val << endl;
if (new_list_head == nullptr) {
new_list_head = p;
j = new_list_head;
} else {
j->next = p;
j = j->next;
}
i = i->next;
}
// step 2, go thru original list and create the link
i = head;
j = new_list_head;
while (i != nullptr) {
j->random = old_to_new[i->random];
i = i->next;
j = j->next;
}
return new_list_head;
}
};