0

I am trying to make a method that removes any value in a linked list that is larger than the input max. I have written out the code and it works for every case except when the first node is greater than the input max value, which then produces a NullPointerException. I was hoping that someone could help me out.

Here is the code I have so far:

public static void removeValuesLargerThanMax(SinglyLinkedList list, int max){
    Node cur = list.head;
    Node prev = null;

    while(cur != null){
        if(cur.data > max){
            prev.next = cur.next;
            cur = cur.next;
            continue;
        }
        prev = cur;
        cur = cur.next;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Roaming
  • 1
  • 1

2 Answers2

0

As you traverse the linked list, you are keeping track of prev, I'm assuming as the previous element in the linked list as you traverse it. However, remember that the first element of a (non-circular) linked list does not have a previous element.

In this case, when you are trying to remove the first element of the linked list, the following code executes:

prev.next = cur.next;
cur = cur.next;

However, the value of prev has not changed since it was initialized to null. Then, this would cause a NullPointerException.

Simply check if prev is null before attempting to update it. You could do something like this (also updating the head pointer):

if(cur.data > max){
    if(prev != null) prev.next = cur.next;
    else list.head = cur.next;
    cur = cur.next;
    continue;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Ryan Zhang
  • 1,856
  • 9
  • 19
0

In this line prev.next = cur.next; when first node is greater than max input then prev value is null. That's why you're getting the error.

Naveen
  • 1