This is a similar problem with 398. Random Pick Index
The following is my solution, which is easy to undersand:
class Solution { int count = 0; Random r = new Random(); ListNode head; public Solution(ListNode head) { this.head = head; ListNode dummy = head; while(dummy!=null){ dummy=dummy.next; count++; } } public int getRandom() { int random = r.nextInt(count); ListNode dummy = head; for(int i=0;i<random;i++){ dummy=dummy.next; } return dummy.val; } }
This is another solution:
class Solution { Random r = new Random(); ListNode head; public Solution(ListNode head) { this.head = head; } public int getRandom() { int count=0; ListNode dummy = head; int res =head.val; while(dummy!=null){ count++; int random = r.nextInt(count); if(random==0) res = dummy.val; dummy = dummy.next; } return res; } }