/**
* 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;
int count = 0;
Random random;
public Solution(ListNode head) {
this.head = head;
random = new Random();
}
public int getRandom() {
int res = 0;
int count = 0;
ListNode cur = head;
while (cur != null) {
count++;
int r = random.nextInt(count) + 1;
if (r == count) {
res = cur.val;
}
cur = cur.next;
}
return res;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
382. 链表随机节点
最新推荐文章于 2025-01-06 23:00:00 发布