-
Notifications
You must be signed in to change notification settings - Fork 0
/
138_CopyListRandomPointer.cpp
48 lines (43 loc) · 1.36 KB
/
138_CopyListRandomPointer.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
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* copy_head = nullptr, *copy_tail = nullptr;
Node *nextptr = nullptr;
// Add the copy nodes after the original nodes
Node* temp = head;
while(temp) {
Node* node = new Node(temp->val);
nextptr = temp->next;
// add the node copy
temp->next = node;
node->next = nextptr;
temp = nextptr;
}
// update the random pointers
temp = head;
while(temp) {
// set the random ptr of cloned node
(temp->next)->random = temp->random ? (temp->random)->next : nullptr;
// next node
temp = temp->next->next;
}
temp = head;
// remove the cloned list
while(temp) {
// remove the cloned node
// when current is the head of cloned list
if(!copy_head) {
copy_head = temp->next;
copy_tail = copy_head;
}
else {
copy_tail->next = temp->next;
copy_tail = copy_tail->next;
}
// disconnect the cloned node
temp->next = (temp->next)->next;
temp = temp->next;
}
return copy_head;
}
};