[英]Stuck inside an infinite loop when adding a node in linked list
我一直在努力弄清楚為什么這段代碼會陷入無限循環。 背后的故事是我找到了解決方案,我將構造函數更改為分配 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;
}
}
錯誤是,它永遠不會終止,因此我認為它永遠在循環。
我認為在您的 add(Node node) 代碼中。 當您添加兩次相同的節點時,它會將下一個指向自身。 因此這將是無限循環。
由於 LinkedList class 的 toString() 方法中的 while 循環,它進入無限循環。
您正在條件驗證
while(current.next != null) { .....}
到達最后一個節點后,您沒有將最后一個節點的下一個節點設置為 null,因此條件永遠不會終止。
要解決此問題,您要添加節點點 node.next = null;
current.next = node;
node.next = null;
++length;
return;
它將終止並且不會在無限循環中 go
代碼中的行不正確是在添加方法“current.next=node”中。 嘗試將其更改為 'current.next=new Node(node.data)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.