gpt4 book ai didi

java - 为什么我的链表赋值的 printList() 方法会出现无限循环?

转载 作者:行者123 更新时间:2023-12-01 19:11:03 25 4
gpt4 key购买 nike

这是我的 printList() 方法的代码:

public String printList() { 

String list = "";
Node tempnode = headNode;

while (tempnode != null) {

list = list + tempnode.data + ", ";
tempnode = tempnode.next;

}

return list;
}

我正在使用 System.out.println(myList.printList()); 调用该方法在我的主要。当我调用该方法时,列表本身是正确的,但列表被打印了无数次,我不明白为什么。如有任何帮助,我们将不胜感激!

最佳答案

如果您的列表是循环的(如 @josejuan 提到的),那么这应该可以解决问题。

public String printList() 
{
String list = "";
Node tempnode = headNode;

while (tempnode != null)
{

list = list + tempnode.data + ", ";
tempnode = tempnode.next;

if ( tempnode == headNode )
{
break;
}
}

return list;
}

关于java - 为什么我的链表赋值的 printList() 方法会出现无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59481805/

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