# [leetcode] 382. Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();


class Solution {
ListNode* hd;
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */

/** Returns a random node's value. */
int getRandom() {
ListNode* node = hd;
int cnt = 0, randVal = 0;
while(node) {
if(rand() % (++cnt) == 0)
randVal = node->val;
node = node->next;
}
return randVal;
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/

wiki上蓄水池抽样的页面，感兴趣的同学可以看下：https://en.wikipedia.org/wiki/Reservoir_sampling