[英]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.