水塘抽样:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/class Solution {ListNode* h;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) {h = head;}/** Returns a random node's value. */int getRandom() {auto cur = h;int val = cur->val, len = 0;while(cur){if(rand() % (len + 1) == 0)val = cur->val;len++;cur = cur->next;}return val;}};/*** Your Solution object will be instantiated and called as such:* Solution* obj = new Solution(head);* int param_1 = obj->getRandom();*/
