程式語言 - LeetCode - C++ - 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 {
private:
    ListNode *head;

public:
    Solution(ListNode* head) {
        this->head = head;
    }
    
    int getRandom() {
        int cnt = 2;
        int ans = head->val;
        ListNode *cur = head->next;

        while (cur) {
            if (rand() % cnt == 0) {
                ans = cur->val;
            }
            cur = cur->next;
            cnt += 1;
        }

        return ans;
    }
};

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