-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.copy-list-with-random-pointer.cpp
More file actions
54 lines (46 loc) · 1.36 KB
/
138.copy-list-with-random-pointer.cpp
File metadata and controls
54 lines (46 loc) · 1.36 KB
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
#include "testharness.h"
#include <string>
#include <string.h>
#include <vector>
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if (head == NULL) return NULL;
// step1: duplicate nodes
RandomListNode* current = head;
while (current != NULL) {
RandomListNode* dup = new RandomListNode(current->label);
dup->next = current->next;
current->next = dup;
current = dup->next;
}
// step2: set random pointers
current = head;
while (current != NULL) {
if (current->random != NULL) {
current->next->random = current->random->next;
}
current = current->next->next;
}
// step3: split lists
RandomListNode* newHead = head->next;
current = head;
while (current != NULL) {
RandomListNode* current2= current->next;
current->next = current2->next;
if (current2->next != NULL) {
current2->next = current2->next->next;
}
current = current->next;
}
return newHead;
}
};
TEST(Solution, test) {
ASSERT_EQ(2, 1+1);
}