Linked List Random Node LeetCode solution in C++

1
/**
2
* Definition for singly-linked list.
3
* struct ListNode {
4
* int val;
5
* ListNode *next;
6
* ListNode() : val(0), next(nullptr) {}
7
* ListNode(int x) : val(x), next(nullptr) {}
8
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9
* };
10
*/
11
class Solution {
12
public:
13
vector<int> v;
14
Solution(ListNode *head) {
15
while (head != NULL) {
16
v.push_back(head->val);
17
head = head->next;
18
}
19
}
20

21
int getRandom() {
22
return v[rand() % v.size()];
23
}
24
};
25

26
/**
27
* Your Solution object will be instantiated and called as such:
28
* Solution* obj = new Solution(head);
29
* int param_1 = obj->getRandom();
30
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0