educative.io

Source of null pointer

I’ve written a solution which avoids iterating through the whole list but it returns a null pointer but I can’t figure it out as the line number is not part of the code I have written. Can anyone help?
public static int findNth(linkedList list, int n) {
Node slow = list.headNode;
Node fast = list.headNode;

    while (n > 0) {
        fast = fast.nextElement;
        n--;
    }

    while (fast.nextElement != null) {
        slow = slow.nextElement;
        fast = fast.nextElement;
    }
    return slow.data;

}

Hi Hasan_Zaidi,

Thanks for reaching out to us!

Two fixes were required in your code:

  1. You were not checking if (n > list size) i.e. if n is greater than the the length of the list under consideration. In this condition the code should return -1; and thats why you were getting NullPointerException.
  2. Your code was returning n-1th node rather than the nth node from the end of the list.

Below is the fixed code:

public static int findNth(linkedList list, int n) {
    Node slow = list.headNode;
    Node fast = list.headNode;

    while (fast.nextElement !=null && n > 0 ) {
      fast = fast.nextElement;
      n--;
    }

    if (fast.nextElement ==null) {
      return -1; 
    }

    while (fast != null) {
      slow = slow.nextElement;
      fast = fast.nextElement;
    }
    return slow.data;
  }

In case of any further queries please feel free to reach out to us.

Best Regards,
Educative Team