Chained list is not removing elements

1

I can not remove elements from the list.

class no {

    public int dado;
    public no prox;
}

class lista {

    no ini;
    no fim;

    public void crialista() {

        ini = null;
        fim = null;
    }

    public void inserir(int num) {
        no novo = new no();
        novo.dado = num;
        novo.prox = null;

        if (ini == null) {
            ini = novo;
        } else {
            fim.prox = novo;
        }
        fim = novo;
    }

    public void imp() {
        no x = ini;
        while (x != null) {
            System.out.println(x.dado);
            x = x.prox;
        }
    }

    public void remover(int num){


    no ant = null;
    no aux = ini;

    do {
    if (aux.dado== num )    
    {
    ant.prox= ant.prox;
    }

    ant = aux;
    aux = aux.prox;
} while (aux!=null);



}

public  class Teste {


    public static void main(String[] args) {

        lista lst = new lista();
        lst.crialista();
        lst.inserir(15);
        lst.inserir(8);
        lst.imp();
        lst.remover (8);
        lst.imp();
    }
}
}
    
asked by anonymous 24.04.2016 / 18:39

1 answer

1

First we will organize the code, mainly giving more meaningful names to be more intuitive what we are doing (at least delete a generic name aux by atual ). It's easy to see the error:

public void remover(int num){
    no ant = null;
    no atual = ini;
    do {
        if (atual.dado == num) {
            ant.prox = atual.prox; //você tem que pegar o próximo do atual
        }
        ant = atual;
        atual = atual.prox;
    } while (atual != null);
}

See running on ideone .

It was not changing at all. It's almost a typo. This happens because the code is not very readable. Many people only understand the power of readability when they start having these problems. Other things could be even more readable. It would be best for ant to become anterior for readability.

This code still has problems. If the list does not have elements gives problem, ideally at least check this situation before doing any operation. Probably only by reversing do-while to while already solves. Of course there will be no crash information, but that's all the code is not worrying about.

If it is to do the ideal, could have a search method and the method of removal would call the search and would only do the removal. Checking for elements could be done by their own method, and so on. Each one with his responsibility without exposing unnecessary details.

I could initialize the list even without a method for this.

    
24.04.2016 / 19:08