-
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
35 lines (34 loc) · 1.02 KB
/
138. Copy List with Random Pointer.cpp
File metadata and controls
35 lines (34 loc) · 1.02 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
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
//unordered_map < RandomListNode *, RandomListNode * > m;
if (head == NULL)return NULL;
unordered_map < int , RandomListNode * > m;
RandomListNode * tmp = head -> next,*tmp1;
RandomListNode *dst = new RandomListNode(head->label);
m[head->label] = dst;
dst->next = NULL;
dst->random = NULL;
tmp1 = dst;
while (tmp){
RandomListNode * node = new RandomListNode(tmp->label);
node->random = tmp->random;
tmp1->next = node;
tmp1 = tmp1->next;
m[tmp->label] = node;
tmp = tmp->next;
}
tmp1->next = NULL;
tmp1 = dst;
tmp = head;
while (tmp1){
if (tmp->random)
tmp1->random = m[tmp->random->label];
else
tmp1->random = NULL;
tmp1 = tmp1->next;
tmp = tmp->next;
}
return dst;
}
};