forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcopy-list-with-random-pointer.cpp
40 lines (36 loc) · 1.12 KB
/
copy-list-with-random-pointer.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
// Time: O(n)
// Space: O(1)
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
// Insert the copied node after the original one.
for (auto *cur = head; cur; cur = cur->next->next) {
auto *node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
}
// Update random node.
for (auto *cur = head; cur; cur = cur->next->next) {
if (cur->random) {
cur->next->random = cur->random->next;
}
}
// Seperate the copied nodes from original ones.
RandomListNode dummy(INT_MIN);
for (auto *cur = head, *copy_cur = &dummy;
cur;
copy_cur = copy_cur->next, cur = cur->next) {
copy_cur->next = cur->next;
cur->next = cur->next->next;
}
return dummy.next;
}
};