链表随机节点返回值listnode

给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。

实现 Solution 类:

Solution(ListNode head) 使用整数数组初始化对象。
int 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*h;
    Solution(ListNode* head) {
        h = head;
    }
    
    int getRandom() {
        int count = 0;
        ListNode*tmp = h;
        while(tmp!=NULL)
        {
            count++;
            tmp=tmp->next;
        }
        int k = rand() % count;
        tmp=h;
        for(int i=0;i<k;i++)
        {
            tmp = tmp->next;
        }
        return tmp->val;
    }
};

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