-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopy_List_with_Random_Pointer.cpp
66 lines (58 loc) · 1.35 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* 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 == NULL)
return NULL;
int size = 1;
RandomListNode *cur = head;
while(cur->next) {
cur = cur->next;
++size;
}
RandomListNode *newAdd[size];
int oldRef[size], oldLabel[size];
memset(oldRef, -1, sizeof(oldRef));
cur = head;
RandomListNode *newHead = NULL, *last = NULL;
for(int i = 0; i < size; ++i) {
RandomListNode *newNode = new RandomListNode(cur->label);
oldLabel[i] = cur->label;
cur->label = i;
if(newHead == NULL)
newHead = newNode;
else
last->next = newNode;
newAdd[i] = newNode;
last = newNode;
cur = cur->next;
}
cur = head;
for(int i = 0; i < size; ++i) {
if(cur->random != NULL)
oldRef[i] = cur->random->label;
cur = cur->next;
}
cur = head;
for(int i = 0; i < size; ++i) {
cur->label = oldLabel[i];
cur = cur->next;
}
cur = newHead;
for(int i = 0; i < size; ++i) {
if(oldRef[i] == -1)
cur->random = NULL;
else
cur->random = newAdd[oldRef[i]];
cur = cur->next;
}
return newHead;
}
};