给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
public class Solution_sushuichi {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
Random ran;
ListNode head;
public Solution_sushuichi(ListNode head) {
this.ran = new Random();
this.head = head;
}
public int getRandom() {
int count = 1;
ListNode cur = head;
ListNode ranNode = head;
while (cur != null) {
if (ran.nextInt(count++) == 0) {
ranNode = cur;
}
cur = cur.next;
}
return ranNode.val;
}
}