Function Delete from the list

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 , does not delete, how do I fix this?

    
asked by anonymous 08.02.2017 / 01:59

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 should check if the head is not null

        if(head == null)
            return;

Next, we check if we should update the root node.

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

Finally we look for the desired value, updating the previous connection 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();
            }
        }
    }
}
    
08.02.2017 / 03:14