Easy Java Solution


  • 0
    E
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public static ListNode head;
        /** @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.head=head;
        }
        
        /** Returns a random node's value. */
        public int getRandom() {
            int len=1;
            ListNode start=head;
            while(start!=null){
                len++;
                start=start.next;
            }
            start=head;
            Random rand=new Random();
            int index=rand.nextInt(len-1);
            while(index!=0 && start!=null){
                start=start.next;index--;
            }
            return start.val;
        }
    }
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution obj = new Solution(head);
     * int param_1 = obj.getRandom();
     */
    

Log in to reply
 

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