-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathcopy-list-with-random-pointer_2(AC).cpp
More file actions
45 lines (42 loc) · 1.08 KB
/
copy-list-with-random-pointer_2(AC).cpp
File metadata and controls
45 lines (42 loc) · 1.08 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
// O(n) solution with hashing
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
typedef RandomListNode RLN;
class Solution {
public:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RLN *copyRandomList(RLN *head) {
if (head == NULL) {
return head;
}
int n, i;
RLN *p;
unordered_map<RLN *, int> um;
vector<RLN *> v;
p = head;
n = 0;
while (p != NULL) {
um[p] = n++;
v.push_back(new RLN(p->label));
p = p->next;
}
for (i = 0; i < n - 1; ++i) {
v[i]->next = v[i + 1];
}
p = head;
for (i = 0; i < n; ++i) {
v[i]->random = p->random != NULL ? v[um[p->random]] : NULL;
p = p->next;
}
return v[0];
}
};