Linked List Random Node LeetCode solution in Java
1class Solution {2int N = 0;3ListNode head = null;45public Solution(ListNode head) {6this.head = head;7}89public int getRandom() {10ListNode p = this.head;11int i = 1, ans = 0;12while (p != null) {13if (Math.random() * i < 1) ans = p.val; // replace ans with i-th node.val with probability 1/i14p = p.next;15i++;16}17return ans;18}19}