Skip to content

Commit aace860

Browse files
committed
Update and rename copyRandomList.cpp to copy-list-with-random-pointer.cpp
1 parent 1dde056 commit aace860

File tree

2 files changed

+40
-40
lines changed

2 files changed

+40
-40
lines changed

C++/copy-list-with-random-pointer.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
/**
5+
* Definition for singly-linked list with a random pointer.
6+
* struct RandomListNode {
7+
* int label;
8+
* RandomListNode *next, *random;
9+
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
RandomListNode *copyRandomList(RandomListNode *head) {
15+
// Insert the copied node after the original one.
16+
for (auto *cur = head; cur; cur = cur->next->next) {
17+
auto *node = new RandomListNode(cur->label);
18+
node->next = cur->next;
19+
cur->next = node;
20+
}
21+
22+
// Update random node.
23+
for (auto *cur = head; cur; cur = cur->next->next) {
24+
if (cur->random) {
25+
cur->next->random = cur->random->next;
26+
}
27+
}
28+
29+
// Seperate the copied nodes from original ones.
30+
RandomListNode dummy(INT_MIN);
31+
for (auto *cur = head, *copy_cur = &dummy;
32+
cur;
33+
copy_cur = copy_cur->next, cur = cur->next) {
34+
copy_cur->next = cur->next;
35+
cur->next = cur->next->next;
36+
}
37+
38+
return dummy.next;
39+
}
40+
};

C++/copyRandomList.cpp

Lines changed: 0 additions & 40 deletions
This file was deleted.

0 commit comments

Comments
 (0)