gpt4 book ai didi

java - 在链表中添加节点时陷入无限循环

转载 作者:行者123 更新时间:2023-11-30 05:26:44 25 4
gpt4 key购买 nike

我一直在努力找出为什么这段代码陷入无限循环。背景故事是我找到了解决方案,我更改了构造函数以分配 head 等于 null 并修复了它。

我想知道为什么这段代码不起作用。

当我添加不同的节点时,它正在工作。代码按预期工作。

添加相同节点时会出现问题。

public class Main {
public static void main(String[] args) {
Node one = new Node(1);
Node two = new Node(2);

LinkedList list = new LinkedList(one);
// this gives error, if i add the same nodes
list.add(two);
list.add(two);

System.out.println("Printing out:\n" + list.toString() +"\n");
}
}


public class LinkedList {
Node head;
int length = 0;
public boolean isEmpty() {
return (head==null);
}

public String toString() {
Node current = head;
String string = "Head: ";

while(current.next != null) {
string += current.toString() + " --> ";
current = current.next;
}
string += current.toString() + " --> " + current.next;
return string;
}

public LinkedList(Node node) {
// if were to set head to null and no arg, it works fine
head = node;
length = 1;
}

public void add(Node node) {
if(isEmpty()) {
System.out.println("Empty list, adding node...");
head = new Node(node.data); ++length;
return;
}
else {

Node current = head;
while(current.next != null) {
current = current.next;
}
//current.next = new Node(node.data);
current.next = node;
++length;
return;
}
}

错误是,它永远不会终止,因此我认为它永远循环。

最佳答案

我认为在您的添加(节点节点)代码中。当您添加相同的节点两次时,它会将下一个节点指向自身。因此这将是无限循环。

关于java - 在链表中添加节点时陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424590/

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