点击打开链接
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
ListNode* cur;
Solution(ListNode* head):cur(head) {
}
/** Returns a random node's value. */
int getRandom() {
ListNode* tem =cur;
int val = cur->val;
for(int i=1; tem; i++){
if(rand()%i==0) val = tem->val;//鱼塘抽样
tem = tem->next;
}
return val;
}
};