-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopy List with Random Pointer.cpp
38 lines (35 loc) · 1.14 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
// Copy List with Random Pointer
/**
* 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) return NULL;
unordered_map<RandomListNode *, RandomListNode *> map;
RandomListNode *dh = new RandomListNode(0);
RandomListNode *cur = head;
RandomListNode *last = dh;
while(cur != NULL) {
if(!map[cur]) {
RandomListNode *newNode = new RandomListNode(cur->label);
map[cur] = newNode;
}
last->next = map[cur];
if(cur->random && !map[cur->random]) {
RandomListNode *newNode = new RandomListNode(cur->random->label);
map[cur->random] = newNode;
}
map[cur]->random = map[cur->random];
last = last->next;
cur = cur->next;
}
delete dh;
return map[head];
}
};