-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
91 lines (81 loc) · 1.61 KB
/
main.cpp
File metadata and controls
91 lines (81 loc) · 1.61 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
int length;
vector<ListNode*>* array;
Solution(ListNode* head)
{
length = 0;
ListNode* ptr = head;
while (ptr != NULL)
{
length++;
ptr = ptr->next;
}
array = new vector<ListNode*>(length);
ptr = head;
for (int i = 0; i < length; ++i)
{
(*array)[i] = ptr;
ptr = ptr->next;
}
srand(time(NULL));
}
~Solution()
{
if (array)
delete array;
}
int getRandom()
{
return (*array)[rand() % length]->val;
}
};
ListNode* create_list(int n)
{
if (n < 1)
return NULL;
ListNode* head = new ListNode(0, NULL);
ListNode* ptr = head;
for (int i = 1; i <= n; ++i)
{
ptr->next = new ListNode(i, NULL);
ptr = ptr->next;
}
return head;
}
void print_n_randoms(Solution& sol, int n)
{
for (int i = 1; i <= n; ++i)
cout << "Random " << i << ": " << sol.getRandom() << endl;
return;
}
void delete_list(ListNode* ptr)
{
ListNode* tmp = ptr->next;
if (tmp)
delete_list(tmp);
delete ptr;
}
int main()
{
ListNode* list = create_list(30);
Solution sol(list);
print_n_randoms(sol, 30);
delete_list(list);
return 0;
}