-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0138.cpp
More file actions
48 lines (45 loc) · 1.25 KB
/
Copy path0138.cpp
File metadata and controls
48 lines (45 loc) · 1.25 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
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
private:
Node* makeTrivialCopy(Node* head, map<Node*,Node*> &m) {
Node* copyHead = new Node(head->val);
m[head] = copyHead;
Node* originalCurrent = head->next, *copyCurrent = copyHead;
while (originalCurrent) {
Node* newNode = new Node(originalCurrent->val);
m[originalCurrent] = newNode;
copyCurrent->next = newNode;
originalCurrent = originalCurrent->next;
copyCurrent = copyCurrent->next;
}
return copyHead;
}
void assignRandomPointers(Node* originalHead, Node* newHead, map<Node*,Node*> &m) {
while (originalHead) {
newHead->random = m[originalHead->random];
originalHead = originalHead->next;
newHead = newHead->next;
}
}
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
map<Node*,Node*> m; // original -> copy
Node* newHead = makeTrivialCopy(head, m);
assignRandomPointers(head, newHead, m);
return newHead;
}
};