-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138. Copy List with Random Pointer.cc
58 lines (50 loc) · 1.3 KB
/
138. Copy List with Random Pointer.cc
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
55
56
57
58
// Using iterative method
// TC: O(n)
// SC: O(n)
/*
// 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) {
if (!head)
return nullptr;
Node* ptr = new Node(head->val);
Node* res = new Node(0, ptr);
unordered_map<Node*, Node*> um({{head, ptr}});
while (head) {
//next
if (head->next == nullptr) {
ptr->next = nullptr;
} else if (um.count(head->next)){
ptr->next = um[head->next];
} else {
ptr->next = new Node(head->next->val);
um[head->next] = ptr->next;
}
//random
if (head->random == nullptr) {
ptr->random = nullptr;
} else if (um.count(head->random)) {
ptr->random = um[head->random];
} else {
ptr->random = new Node(head->random->val);
um[head->random] = ptr->random;
}
head = head->next;
ptr = ptr->next;
}
return res->next;
}
};