-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy_list_random_pointer.cpp
61 lines (56 loc) · 1.51 KB
/
copy_list_random_pointer.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copy list with random pointer
# Brute Force Approach
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*,Node*> hashMap;
Node* temp = head;
while(temp != NULL) {
Node* newNode = new Node(temp->val);
hashMap[temp] = newNode;
temp = temp->next;
}
Node* t = head;
while(t != NULL) {
Node* node = hashMap[t];
node->next = (t->next != NULL) ? hashMap[t->next]:NULL;
node->random = (t->random != NULL) ? hashMap[t->random]:NULL;
t = t->next;
}
return hashMap[head];
}
};
# Optimized Approach
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* temp = head;
//step 1
while(temp != NULL) {
Node* newNode = new Node(temp->val);
newNode->next = temp->next;
temp->next = newNode;
temp = temp->next->next;
}
//step 2
Node* itr = head;
while(itr != NULL) {
if(itr->random != NULL)
itr->next->random = itr->random->next;
itr = itr->next->next;
}
//step 3
Node* dummy = new Node(0);
itr = head;
temp = dummy;
Node* fast;
while(itr != NULL) {
fast = itr->next->next;
temp->next = itr->next;
itr->next = fast;
temp = temp->next;
itr = fast;
}
return dummy->next;
}
};