Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();


 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     List<Integer> list = new ArrayList<>();
11     
12     /** @param head The linked list's head.
13         Note that the head is guaranteed to be not null, so it contains at least one node. */
14     public Solution(ListNode head) {
15         while (head != null) {
16             list.add(head.val);
17             head = head.next;
18         }
19     }
20     
21     /** Returns a random node's value. */
22     public int getRandom() {
23         Random rand = new Random();
24         int n = rand.nextInt(list.size());
25         return list.get(n);
26     }
27 }
28 
29 /**
30  * Your Solution object will be instantiated and called as such:
31  * Solution obj = new Solution(head);
32  * int param_1 = obj.getRandom();
33  */
原文地址:https://www.cnblogs.com/amazingzoe/p/6416727.html