给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样
class Solution {
private ListNode head;
public Solution(ListNode head) {
this.head = head;
}
public int getRandom() {
int res = head.val;
ListNode no = head.next;
int i = 2;
Random random = new Random();
while(no!=null){
if(random.nextInt(i) == 0){
res = no.val;
}
i++;
no = no.next;
}
return res;
}
}