【发布时间】:2020-02-13 21:36:57
【问题描述】:
我一直在努力弄清楚为什么这段代码会陷入无限循环。背后的故事是我找到了解决方案,我将构造函数更改为分配 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 methods linked-list infinite-loop singly-linked-list