382. 链表随机节点
简单
cpp
class Solution {
public:
int n;
ListNode* head;
Solution(ListNode* head) {
int cnt = 0;
this->head = head;
while(head != 0)
{
head = head->next;
++cnt;
}
n = cnt;
}
int getRandom() {
int idx = rand() % n;
ListNode* h = head;
while(idx != 0)
{
h = h->next;
idx--;
}
return h->val;
}
};