Delete function from list

Asked

Viewed 54 times

2

I have this function to delete from the list chained by value:

public void deletar(Object valor) {
        Node temp = head;

        while(temp != null) {
            if(temp.getNext().getValor().equals(valor))  {
                temp.setNext(temp.getNext().getNext());
                break;
            } else { 
                temp = temp.getNext();
            }
        }
    }

But the last element always causes NullPointerException, do not delete, how do I solve this?

1 answer

2


The problem is that you are trying to call temp.getNext(). getNext(), but the first call of getNext() can return null, and this is not being checked.

First we must check if the head is non-zero

        if(head == null)
            return;

Then we check if we should upgrade the root node.

        if(head.getValor().equals(valor)){
            head = head.getNext();
            return;
        }

Finally we seek the desired value by updating the previous link temp:

        temp = head;
        prox = temp.getNext();
        while(prox != null) {
            if(prox.getValor().equals(valor))  {
                temp.setNext(prox.getNext());
                break;
            } else { 
                temp = prox;
                prox = temp.getNext();
            }
        }
    }
}

The complete Code is as follows::

public void deletar(Object valor) {
        Node temp, prox;

        if(head == null)
            return;

        if(head.getValor().equals(valor)){
            head = head.getNext();
            return;
        }

        temp = head;
        prox = temp.getNext();

        while(prox != null) {
            if(prox.getValor().equals(valor))  {
                temp.setNext(prox.getNext());
                break;
            } else { 
                temp = prox;
                prox = temp.getNext();
            }
        }
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.