Search code examples
javalistnodes

Remove duplicates in a linked list in java


I try to remove duplicates in a simple list with the following code:

public void eliminarRepetidos(){
    if(this.isEmpty())
        return;

    for(Nodo<T> n = this.cab; n!=null; n=n.getSiguiente()){
        for(Nodo<T> m = n.getSiguiente(); m!=null; m=m.getSiguiente()){
            if(n.getInfo() == m.getInfo()){
                eliminar(m);
            }
        }
    }
}


private void eliminar(Nodo<T> m){
    Nodo<T> aux =this.cab;
    while(aux.getSiguiente()!= m){
        aux = aux.getSiguiente();
    }
    aux.setSiguiente(m.getSiguiente());
    m.setSiguiente(null);
    this.tam--;
}

If the list is empty nothing will be executed.if (isEmpty ()) If the list has elements then I proceed to delete taking as a reference the head node which in this case would be node n that is in the first for. node m will always be positioned ahead of node n (Second for), m will iterate looking for matches and if it finds any, it will eliminate said node (m), that is, eliminate (m) ;.

When entering the delete method (Node m) what I do is create an auxiliary node (Aux node) and this will iterate until it is the previous one to the node m passed by parameter, this in order not to lose the continuity of the list.

At the time of testing, I enter the Integer data list: 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> null

You should give me an answer 1-> null.

But it doesn't delete them all, the output is as follows: 1-> 1-> 1-> 1-> 1-> null

I have tried for a while and cannot eliminate them all, what am I failing? Or what do I have to correct for the code to work?


Solution

  • because you are doing

    eliminar(m);
    

    and the for at the end of the iteration is doing

    m.getSiguiente();
    

    which will return null because inside eliminar you have set the siguente to null... instead you should do this inside the second loop:

    Nodo<T> tmp = m.getSiguiente();
    eliminar(m);
    m = tmp;