文章目录
题目描述
思路
复杂度
时间复杂度:
空间复杂度:
Code
/**
* 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 {
ListNode *head;
public:
Solution(ListNode* head) {
this -> head = head;
}
/**
* Returns a random node of the linked list
*
* @return int
*/
int getRandom() {
int res = 0;
ListNode* node = head;
int i;
for (int i = 1; node != nullptr; ++i) {
if (rand() % i == 0) {
res = node -> val;
}
node = node -> next;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/