forked from pezy/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.h
29 lines (27 loc) · 955 Bytes
/
solution.h
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
#include <cstddef>
#include <unordered_map>
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
};
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
std::unordered_map<RandomListNode*, RandomListNode*> map;
RandomListNode preHead(0);
for (RandomListNode *next = &preHead; head; next = next->next, head = head->next) {
if (map[head] == NULL) {
RandomListNode* node = new RandomListNode(head->label);
map[head] = node;
}
next->next = map[head];
if (head->random && map[head->random] == NULL) {
RandomListNode* node = new RandomListNode(head->random->label);
map[head->random] = node;
}
map[head]->random = map[head->random];
}
return preHead.next;
}
};