forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy_List_With_Random_Pointer.cc
40 lines (38 loc) · 1.12 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
39
40
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
RandomListNode *ret = NULL, *tmp = head, *entry = NULL;
RandomListNode **pCur = &ret;
while (tmp) {
entry = tmp;
tmp = tmp->next;
entry->next = new RandomListNode(entry->label);
entry->next->next = tmp;
}
tmp = head;
while (tmp) {
entry = tmp->next;
if (tmp->random)
entry->random = tmp->random->next;
tmp = entry->next;
}
tmp = head;
while (tmp) {
entry = tmp->next;
*pCur = entry;
tmp->next = entry->next;
tmp = tmp->next;
pCur = &((*pCur)->next);
}
return ret;
}
};