[英]Infinite loop when iterating through Linked List
我試圖計算在我的鏈接列表中發生特定整數的時間。 但是我遇到了無限循環。 我嘗試打印變量以查看代碼到達的位置但沒有打印。 我想知道是否有人可以為我增加一雙眼睛。
我的LinkedListNode
類很簡單:
public class LinkedListNode {
int data;
public LinkedListNode next;
// constructor
public LinkedListNode(int newData) {
this.next = null;
this.data = newData;
}
}
我的代碼:
public static int countInt(LinkedListNode head, int number) {
int count = 0;
while (head.next != null) {
if (head.data == number) {
count++;
//System.out.println(count);
head = head.next;
//System.out.println(head.data);
}
}
return count;
}
你應該將head
到下一個節點,即使if
不滿足。
當前節點等於您發送到countInt
的數字時,您只能移動到下一個節點。
從while循環中移動head = head.next
將有助於無限循環,但是你需要檢查head是否為null,而不是head.next,因此while循環將檢查最后一個元素的值
public static int countInt(LinkedListNode head, int number) {
int count = 0;
while (head != null) {
if (head.data == number) {
count++;
//System.out.println(count);
//System.out.println(head.data);
}
head = head.next;
}
return count;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.