Am I doing something wrong here?


  • 0
    D
    public class Solution {
        ListNode top;
        /** @param head The linked list's head.
            Note that the head is guaranteed to be not null, so it contains at least one node. */
        public Solution(ListNode head) {
            this.top = head;
        }
        
        /** Returns a random node's value. */
        public int getRandom() {
            ListNode n = this.top;
            int size = size(top);
            int i = 1;
            Random rand = new Random();
            int stop = rand.nextInt(size);
            int ans = 0;
            while(n != null && i < stop){
                ans = n.val;
                i++;
                n = n.next;
            }
            return ans;
        }
        
        public int size(ListNode head){
            int count = 0;
            ListNode n = head;
            while(n != null){
                count++;
                n = n.next;
            }
            return count;
        }
    }
    

    It gets the right answer when I click "Run Code" sometimes but I thought that was the point of it being random.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.