-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCopy-list-with-random-pointer.cc
38 lines (38 loc) · 1.09 KB
/
Copy-list-with-random-pointer.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
/**
* 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) {
if(head == nullptr) return nullptr;
RandomListNode *cur(head), *node(nullptr);
while(cur) {
node = new RandomListNode(cur->label);
node->next = cur->next;
cur->next = node;
cur = cur->next->next;
}
//set the random pointer
cur = head;
while(cur) {
if(cur->random) cur->next->random = cur->random->next; //别忘了判断非空
cur = cur->next->next;
}
//separate lists
RandomListNode dummy(-1), *rear(&dummy);
cur = head;
while(cur) {
node = cur->next;
cur->next = cur->next->next;
rear->next = node;
rear = rear->next;
cur = cur->next;
}
return dummy.next;
}
};