gpt4 book ai didi

java - 删除重复节点

转载 作者:行者123 更新时间:2023-12-01 05:06:58 34 4
gpt4 key购买 nike

我迷路了,真的希望有人能帮助我,我应该创建一个函数来查找重复的数字节点并删除重复项。每当我运行整个代码时,我都会陷入 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com