-
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
58 lines (50 loc) · 1.06 KB
/
Copy path138.copy-list-with-random-pointer.cpp
File metadata and controls
58 lines (50 loc) · 1.06 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
49
50
51
52
53
54
55
56
57
/*
* @lc app=leetcode id=138 lang=cpp
*
* [138] Copy List with Random Pointer
*/
// @lc code=start
#include "bits/stdc++.h"
using namespace std;
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = nullptr;
random = nullptr;
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return nullptr;
unordered_map<Node*, Node*> old2new;
Node *node = head;
while (node) {
old2new[node] = new Node(node->val);
node = node->next;
}
node = head;
while (node) {
if (node->next)
{
old2new[node]->next = old2new[node->next];
}
if (node->random)
{
old2new[node]->random = old2new[node->random];
}
node = node->next;
}
return old2new[head];
}
};
int main() {
Solution sol;
Node* head = new Node(7);
sol.copyRandomList(head);
}
// @lc code=end