-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
138. Copy List with random pointer
40 lines (36 loc) · 1.05 KB
/
138. Copy List with random pointer
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
// Here is the solution of this question without using map
// It's is much optimized
solution in C++
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return 0;
// step 1: clone a -> a'
Node* it = head;
while(it){
Node*clonedNode = new Node(it->val);
clonedNode->next = it->next;
it->next = clonedNode;
it = it->next->next;
}
//step 2: assign random links of A with the help of random pouinter
it = head;
while(it){
Node*clonedNode = it->next;
clonedNode->random = it->random ? it->random->next : nullptr;
it = it->next->next;
}
//step 3: detatch A from A
it = head;
Node*clonedHead = it->next;
while(it){
Node*clonedNode = it->next;
it->next = it->next->next;
if(clonedNode->next){
clonedNode->next = clonedNode->next->next;
}
it = it->next;
}
return clonedHead;
}
};