1.题目要求:
2.题目代码:
/*** 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> array;Solution(ListNode* head) {ListNode* cur = head;while(cur){array.push_back(cur->val);cur = cur->next;}//设置随机种子srand((unsigned)time(NULL));}int getRandom() {//控制随机范围int randomindex = rand() % array.size();return array[randomindex];}
};/*** Your Solution object will be instantiated and called as such:* Solution* obj = new Solution(head);* int param_1 = obj->getRandom();*/