Description
Submission
/**
* 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 {
int count;
ListNode* head;
public:
Solution(ListNode* head) {
count = 0;
for(ListNode* ptr = head; ptr != nullptr; ptr = ptr->next) ++count;
this->head = head;
}
int getRandom() {
int n = rand() % count;
ListNode* ptr = head;
for(int i = 0; i < n; ++i) ptr = ptr->next;
return ptr->val;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/