-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.cpp
More file actions
140 lines (126 loc) · 2.71 KB
/
138.cpp
File metadata and controls
140 lines (126 loc) · 2.71 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
// 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 NULL;
unordered_map<Node*, Node*> ump;
Node* trav = head;
Node* res = new Node(0);
Node* curr = res;
while(trav){
curr->next = new Node(trav->val);
curr = curr->next;
ump[trav] = curr;
trav = trav->next;
}
trav = head;
while(trav){
if(trav->random){
ump[trav]->random = ump[trav->random];
}
trav = trav->next;
}
return res->next;
}
};
//Single PASS
/*
// 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:
unordered_map<Node*, Node*> ump;
Node* getCloned(Node* head){
if(!head)
return NULL;
if(!ump.count(head))
ump[head] = new Node(head->val);
return ump[head];
}
Node* copyRandomList(Node* head) {
if(!head)
return NULL;
Node* old = head;
Node* curr = new Node(old->val);
ump[old] = curr;
while(old){
curr->random = getCloned(old->random);
curr->next = getCloned(old->next);
old = old->next;
curr = curr->next;
}
return ump[head];
}
};
// O(1) space
// idea is to store the new node as
// A->B->C to A->A'->B->B'->C->C'
/*
// 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 NULL;
Node* curr = head;
while(curr){
Node* nxt = new Node(curr->val);
nxt->next = curr->next;
curr->next = nxt;
curr = nxt->next;
}
curr = head;
while(curr){
if(curr->random)
curr->next->random = curr->random->next;
curr = curr->next->next;
}
curr = head;
Node* res = head->next;
Node* now = head->next;
while(curr){
curr->next = curr->next->next;
res->next = (res->next!=NULL)?res->next->next:NULL;
curr = curr->next;
res = res->next;
}
return now;
}
};