https://leetcode.com/problems/linked-list-random-node/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
水塘抽样:维护一个大小为1的水塘,由于确定head一定存在,定义res返回head->val的值,然后让head指向下一个节点,同时定义一个变量i,i初始化为2,当cur不为空的时候,循环在[0,i-1]中取值,变量i自增1,cur指向下一个位置,如果随机生成数为0的话,交换水塘的值和当前遍历的值。这样保证每个数字的概率。
*/
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
this->head=head;
}
/** Returns a random node's value. */
int getRandom() {
int res=head->val;
int i=2;
ListNode *cur=head->next;
while(cur){
int j=rand()%i;
if(j==0) res=cur->val;
++i;
cur=cur->next;
}
return res;
}
private:
ListNode *head;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/