题目
https://leetcode-cn.com/problems/linked-list-random-node/
代码
/**
* 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 {
ListNode head;
Random random;
public Solution(ListNode head) {
this.head=head;
this.random=new Random();
}
public int getRandom() {
int res=0;
int i=1;
for(ListNode node=head;node!=null;node=node.next){
if(random.nextInt(i)==0){//生成[0,i)
res=node.val;
}
i++;
}
return res;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/