rand()就可以了
/** * 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: long long length; ListNode* h; Solution(ListNode* head) { long long len = 0; ListNode* p = head; while(p) { len++; p = p->next; } length = len; h = head; } int getRandom() { long long cnt = 0; long long k = rand() % length; ListNode* p = h; while(p && cnt < k) { cnt++; p = p->next; } return p->val; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */