水塘抽样:

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. class Solution {
    10. ListNode* h;
    11. public:
    12. /** @param head The linked list's head.
    13. Note that the head is guaranteed to be not null, so it contains at least one node. */
    14. Solution(ListNode* head) {
    15. h = head;
    16. }
    17. /** Returns a random node's value. */
    18. int getRandom() {
    19. auto cur = h;
    20. int val = cur->val, len = 0;
    21. while(cur)
    22. {
    23. if(rand() % (len + 1) == 0)
    24. val = cur->val;
    25. len++;
    26. cur = cur->next;
    27. }
    28. return val;
    29. }
    30. };
    31. /**
    32. * Your Solution object will be instantiated and called as such:
    33. * Solution* obj = new Solution(head);
    34. * int param_1 = obj->getRandom();
    35. */