java - 删除重复节点

标签 java duplicates nodes

我迷路了,真的希望有人能帮助我,我应该创建一个函数来查找重复的数字节点并删除重复项。每当我运行整个代码时,我都会陷入 while(current.next != null) 内的无限循环。

我的主要问题是,我知道我的问题出在 if (tester.data == current.data) 中。我不明白为什么他们从不测试或比较(他们的整数)。如果这是一个模糊的问题,我很抱歉,我已经困惑地盯着屏幕好几个小时了。

public void removeDuplicate()
{
    // removes all duplicate nodes from the list

    Node tester = head;
    Node previous = head;
    Node current = head.next;

    while (tester.next != null){
        int i = 0;
        while(current.next != null){
            System.out.println("Stuck here3");
            if (tester.data == current.data){
            Node tempNode = current.next;
                previous.next = tempNode;
                current = tempNode;
                size--;
                System.out.println("Stuck here2");
                break;
                }

            else{   
                previous = current;
                current = current.next;
            }

        }
        System.out.println("Stuck here1");
        tester = tester.next;
        current = tester.next;
    }

}

最佳答案

My main question is, I know my problem resides in if (tester.data == current.data). I do not understand why they never test or compare (their ints). I am sorry if this is a vague question I have been staring at my screen baffled for hours.

不,这不是你的问题。事实上,他们确实进行了测试和比较,并且当发生这种情况时,节点的删除就起作用了。

但是,您的代码中还存在其他问题。

由于内部循环中的 break,您只能为每个值删除一个重复项。

如果你删除那个break,它会变得更接近,但在循环结束时,你会得到

    tester = tester.next;
    current = tester.next;

并且您没有将 previous 设置为适当的新值。

应该是

    tester = tester.next;
    previous = tester;
    current = tester.next;

完成这两项更改后,您的代码将删除所有重复项,除非出现在列表最末尾的重复项。

我怀疑我也可以解决这个问题,但我更倾向于完全重写。如果我这样做,我可以发布它。

关于java - 删除重复节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522276/

相关文章:

swift - 如何在不同类的循环中生成 SKnode - swift

java - Java中的继承和静态成员

java - jdbc sql server错误: java. sql.SQLException:没有合适的驱动程序

python-3.x - Pandas 有条件地组合(和求和)行

java - 避免数组中出现重复的条目

具有 3 个结构值的 C++ 二叉树

java - 如何在 Eclipse 中强制 JFace 向导的最小高度?

java - ConcurrentHashMap 中的 keySet(VmappedValue) 究竟是如何工作的?

list - 识别列表中连续重复项的最 Pythonic 方法是什么?

c - 不允许指向不完整类类型的指针 - 单链表