/*
* 382. Linked List Random Node
* 2016-8-20 by Mingyang
* 直接进行长度计算就好了,再根据随机数,便利到指定的位置找到结果
*/
class Solution {
int len = 0;
ListNode head;
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
this.head = head;
ListNode cur = head;
while(cur!=null){
len++;
cur = cur.next;
}
}
/** Returns a random node's value. */
public int getRandom() {
int r = (int)(Math.random() * len);
ListNode cur = head;
while(r > 0){
cur = cur.next;
r--;
}
return cur.val;
}
}