/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
private ListNode head;
public Solution(ListNode head) {
this.head = head;
}
public int getRandom() {
//直接假设袋子容量为1
int count = 1;
int res = head.val;
ListNode temp = head;
temp=temp.next;
while (temp != null) {
count++;
if (rand(count) == 1) {//第 i 个数被替换(cur进入蓄水池)的概率为1/count,前面第i个数不被替换(cur不进入蓄水池)的概率为(count-1)/count,如此可以做到每个数被保留的概率为m/N
res = temp.val;
}
temp = temp.next;
}
return res;
}
public int rand(int max){
return (int)(Math.random()*max)+1;
}
}