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*/11class Solution {12public:13vector<int> v;14Solution(ListNode *head) {15while (head != NULL) {16v.push_back(head->val);17head = head->next;18}19}2021int getRandom() {22return v[rand() % v.size()];23}24};2526/**27* Your Solution object will be instantiated and called as such:28* Solution* obj = new Solution(head);29* int param_1 = obj->getRandom();30*/