题目如上
要实现一个位置长度的链表里面取每个数都随机,可以把链表里的值都压进vector里,为什么要用vector,因为可以开始不用设定长度,然后最后用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:
vector<int>ans;
Solution(ListNode* head) {
while(head)
{
ans.push_back(head->val);
head=head->next;
}
}
int getRandom() {
return ans[rand()%ans.size()];
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/