# 382. Linked List Random Node (Medium)

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.

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].

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

## Solutions

``````class Solution {

// To calculate the probability of a particular node, the idea is as follows.
// Cursor start from head to tail of the list. Particular node happens to be chose
// when the cursor moves to it, meanwhile the subsequent nodes are not chosen during traverse.

// for node n-2, the probability of being chosen is (1/(n-2)) * ((n-2)/(n-1)) * ((n-1)/n) = 1/n
// for node n-1, the probability of being chosen is (1/(n-1)) * ((n-1)/n) = 1/n
// for node n, the probability of being chosen is 1/n

Random random;

this.random = new Random();
}

public int getRandom() {

for (int i = 1; cur != null; i++) {
if (random.nextInt(i) == 0) {
ans = cur;
}

cur = cur.next;
}

return ans.val;
}
}
``````