-
Notifications
You must be signed in to change notification settings - Fork 6
/
copy_list_with_random_ptr.cpp
105 lines (84 loc) · 2.27 KB
/
copy_list_with_random_ptr.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
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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
/*
"""
Step 1: Clone list and fix the next pointers
|----------------------|
|----------------------v v
[1 -> 1` -> 2 -> 2` -> 3 -> 3` -> 4 -> 4`]
Step 2: Fix the random pointers
|----------------------|
|----------------------v v
[1 -> 1` -> 2 -> 2` -> 3 -> 3` -> 4 -> 4`]
@ # @ #
@@@@@@@@@@@@@@@@@@@@@@@@ #
# #
########################
Step 3: Split the cloned list
|---------|
|---------v v
[1 -> 2 -> 3 -> 4]
[1` -> 2` -> 3` -> 4`]
@ # @ #
@@@@@@@@@@@@@ #
# #
#############
"""
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
// auto current_node = head;
// map<Node*, Node*> mp;
// //step 1: copy nodes
// while(current_node) {
// mp[current_node] = new Node(current_node->val);
// current_node = current_node->next;
// }
// //step 2: fix random and next pointers
// current_node = head;
// while(current_node) {
// mp[current_node]->next = mp[current_node->next];
// mp[current_node]->random = mp[current_node->random];
// current_node = current_node->next;
// }
// return mp[head];
if(!head) return NULL;
auto l1 = head;
Node* l2 = NULL;
while(l1) {
l2 = new Node(l1->val);
l2->next = l1->next;
l1->next = l2;
l1 = l1->next->next;
}
l1 = head;
while(l1) {
if(l1->random) l1->next->random = l1->random->next;
l1 = l1->next->next;
}
l1 = head;
auto l2_head = l1->next;
while(l1) {
l2 = l1->next;
l1->next = l2->next;
if(l2->next) {
l2->next = l2->next->next;
}
l1 = l1->next;
}
return l2_head;
}
};