【leetcode 蓄水池抽样 C++】382. Linked List Random Node

382. Linked List Random Node

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* head;
    ListNode* p;
    /** @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 ans = 0, cnt = 0;
        p = head;
        while(p) {
    
    
            if(rand() % ++cnt == 0) ans = p->val;
            p = p->next;
        }
        return ans;
    }
};

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

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* head;
    ListNode* p;
    int len = 0;
    /** @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() {
    
    
        for(p = this->head, len = 0; p; p = p->next, len++);
        int rand_num = rand() % len;
        for(p = this->head, len = 0; len != rand_num; p = p->next, len++);
        return p->val;
    }
};

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

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/114185907