question about java.lang.NullPointerException

  • 0

    Hi all,
    When I run my code on the OJ it points out that for the following code I made a null pointer exception.

    int res=head.val;

    but isn't the input are guaranteed that the head is not null?
    Can anybody figure out what is happening? I am not familiar with java and appreciate for any help.
    Here attaches all the code.

       ListNode head;
       Random random;
        /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
        public Solution(ListNode head) {
            this.head = head;
            random = new Random();
        /** Returns a random node's value. */
        public int getRandom() {
            int res=head.val;
            for(int count=1;head!=null;count++){
            return res;

  • 0

    same question

Log in to reply

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