-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyListwithRandomPointer.cpp
More file actions
46 lines (42 loc) · 1006 Bytes
/
copyListwithRandomPointer.cpp
File metadata and controls
46 lines (42 loc) · 1006 Bytes
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
// Source: https://leetcode.com/problems/copy-list-with-random-pointer/
// Author: Miao Zhang
// Date: 2021-01-21
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
unordered_map<Node*, Node*> dicts;
Node* dummy = new Node(0);
Node* newhead = dummy;
Node* tmp = head;
while (tmp) {
Node* node = new Node(tmp->val, nullptr, nullptr);
dicts[tmp] = node;
newhead->next = node;
tmp = tmp->next;
newhead = newhead->next;
}
tmp = head;
while (tmp) {
if (tmp->random) {
dicts[tmp]->random = dicts[tmp->random];
}
tmp = tmp->next;
}
return dummy->next;
}
};