-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_list_with_random_pointer.cpp
More file actions
54 lines (45 loc) · 1.03 KB
/
copy_list_with_random_pointer.cpp
File metadata and controls
54 lines (45 loc) · 1.03 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
/*
// 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) {
unordered_map<Node*, Node*> map;
Node* new_head = nullptr;
Node* tail;
Node* search = head;
while(search){
if(new_head == nullptr){
new_head = new Node(search->val);
tail = new_head;
}else{
tail->next = new Node(search->val);
tail = tail->next;
}
map[search] = tail;
search = search->next;
}
search = head;
tail = new_head;
while(search){
if(search->random)
tail->random = map[search->random];
else
tail->random = nullptr;
search = search->next;
tail = tail->next;
}
return new_head;
}
};