简体   繁体   English

删除 java 中链表中的重复项

[英]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.如果列表为空,则不会执行任何操作。if (isEmpty ()) 如果列表有元素,那么我继续删除以头节点为参考,在这种情况下,头节点将是第一个节点 n。 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);.节点 m 将始终位于节点 n 之前(第二个),m 将迭代寻找匹配项,如果找到匹配项,则消除该节点(m),即消除(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.当进入delete方法(节点m)我所做的是创建一个辅助节点(辅助节点),这将迭代直到它是通过参数传递的节点m的前一个,这是为了不失去列表的连续性.

At the time of testing, I enter the Integer data list: 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> 1-> null在测试的时候,我进入Integer数据列表:1->1->1->1->1->1->1->1->1->1->null

You should give me an answer 1-> null.你应该给我一个答案 1-> null。

But it doesn't delete them all, the output is as follows: 1-> 1-> 1-> 1-> 1-> null但它并没有全部删除,output如下: 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?或者我必须纠正什么代码才能工作?

because you are doing因为你在做

eliminar(m);

and the for at the end of the iteration is doing迭代结束时的 for 正在做

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:这将返回null因为在eliminar内部您已将 siguente 设置为siguente ... 而您应该在第二个循环中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM