题目链接:https://leetcode-cn.com/problems/linked-list-random-node/
题目如下:
/**
* 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:
ListNode* p;
Solution(ListNode* head) {
p=head;
}
int getRandom() {
int res=0;
int cnt=0;
auto temp=p;
while(temp){
cnt++;
if(rand()%cnt==0) res=temp->val;
temp=temp->next;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/