382. Linked List Random Node

蓄水池原理

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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) {
        p=head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        int val=p->val;
        int i=2;
        ListNode* cur=p->next;
        while(cur){
            int j=rand()%i;
            if(j==0) val=cur->val;
            i++;cur=cur->next;
        }
        return val;
    }
private:
    ListNode* p;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */
原文地址:https://www.cnblogs.com/bright-mark/p/9603861.html