-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path138.cpp
44 lines (36 loc) · 1.17 KB
/
138.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
// 138. Copy List with Random Pointer - https://leetcode.com/problems/copy-list-with-random-pointer
#include "bits/stdc++.h"
using namespace std;
// 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 {
private:
unordered_map<RandomListNode*, RandomListNode*> hashmap;
void checkAndMaybeCreateDuplicate(RandomListNode* node) {
if (node == nullptr) { return; }
if (hashmap.count(node)) { return; }
hashmap[node] = new RandomListNode(node->label);
}
public:
RandomListNode *copyRandomList(RandomListNode *head) {
auto cur = head;
while (cur != nullptr) {
auto vec = {cur, cur->next, cur->random};
for (auto node : vec) {
checkAndMaybeCreateDuplicate(node);
}
hashmap[cur]->next = hashmap[cur->next];
hashmap[cur]->random = hashmap[cur->random];
cur = cur->next;
}
return hashmap[head];
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}