-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcopyRandomList.cpp
57 lines (42 loc) · 1.22 KB
/
copyRandomList.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
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
// 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 head;
unordered_map<Node*, Node*> m;
Node *clonedHead = new Node(head->val);
Node *newHead = clonedHead;
Node *oldHead = head;
m[oldHead]=newHead;
while(oldHead->next){
newHead->next = new Node(oldHead->next->val);
oldHead = oldHead->next;
newHead = newHead->next;
m[oldHead]=newHead;
}
oldHead = head;
newHead = clonedHead;
while (oldHead && newHead){
// If random exists
if (oldHead->random != NULL){
newHead->random = m[oldHead->random];
}
oldHead = oldHead->next;
newHead = newHead->next;
}
return clonedHead;
}
};