-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138. Copy List with Random Pointer_spaceConstant.cc
56 lines (51 loc) · 1.32 KB
/
138. Copy List with Random Pointer_spaceConstant.cc
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
// Using O(1) space method without hash table
//TC: O(n)
//SC: O(1)
/*
// 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) {
Node* curr = head;
//Every original node owns a copied node and puts it behind itself.
//only deal with "next" pointer part of "head" list.
while (curr) {
Node* t = new Node(curr->val);
t->next = curr->next;
curr->next = t;
curr = t->next;
}
curr = head;
//only deal with "random" pointer part of "head" list.
while (curr) {
if (curr->random){
//curr->random->next: point to copied node
curr->next->random = curr->random->next;
}
curr = curr->next->next;
}
//Remove the redudant links
Node* dummyNode = new Node(-1);
Node* tail = dummyNode;
curr = head;
while (curr) {
tail->next = curr->next;
curr->next = curr->next->next;
curr = curr->next;
tail = tail->next;
}
return dummyNode->next;
}
};