0

I'm trying to write a method that removes all instances of a value from a singly linked list, but I'm having some trouble. I'm receiving a nullpointerexception on line 8 of this code:

public void remove (int value)
{
    IntegerNode temp=head;
    while (temp !=null)
    {
        if (temp.value == value)
        {
            temp.next = temp.next.next;
            count--;
        }
        temp=temp.next;
    }
}

Not certain what it is I'm doing that's bringing up this error...

5 Answers 5

2

Make sure that temp.next is not null in

 temp.next.next;

It is safer to use as follows

 public void remove (int value){
  IntegerNode temp=head;
  while (temp !=null){
    if (temp.value == value){
       if(temp.next!=null){
          temp.next = temp.next.next;
          count--;
        }          
      }
    temp=temp.next;
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

0

As I read it, you want to remove temp from your list if temp.value equals value. However, your code has a few errors:

  1. your code tries to remove temp.next instead of temp.
  2. When temp.value equals value in the last element (where temp.next == null), the line temp.next = temp.next.next will trigger your NullPointerException.

Comments

0

This will fail in the last iteration:

temp.next = temp.next.next;

For the last node, temp.next will be null as a result temp.next.next will throw NPE.

Comments

0

Change your if condition a bit cause the error might be coming when temp->next is null and you do temp->next->next.

if (temp.value == value)
        {
        if(temp.next != null)
            {
            temp.next = temp.next.next;
            }
            count--;
        }

Comments

0

Your code is trying to remove temp.next instead of temp.

public  void removeAll(int element){
    Node node = head;
    Node prev = null;
    while (node != null){
        if(node.key == element){
            if(node == head)
                head = node.next;
            else
                prev.next = node.next;
        }
        else
            prev = node;
        node = node.next;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.