Java 遍历链表时的无限循环

Java 遍历链表时的无限循环,java,linked-list,Java,Linked List,我试图计算一个特定整数在我的链表中出现的时间。然而,我遇到了一个无限循环。我试图打印变量以查看代码到达的位置,但没有打印任何内容。我想知道是否有人能给我多一双眼睛 我的LinkedListNode类只是: public class LinkedListNode { int data; public LinkedListNode next; // constructor public LinkedListNode(int newData) { t

我试图计算一个特定整数在我的链表中出现的时间。然而,我遇到了一个无限循环。我试图打印变量以查看代码到达的位置,但没有打印任何内容。我想知道是否有人能给我多一双眼睛

我的
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;
}

您应该将
移动到下一个节点,即使
如果
不满足要求。

只有当当前节点等于您发送到
countInt
的数目时,您才移动到下一个节点
head=head.next
out of the while循环将有助于无限循环,但您需要检查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;
}

没有看到这个谢谢!对我来说已经很晚了@狮子座:没问题,这就是为什么世界上有白天和黑夜:)白天的人帮助晚上的人;)我以为世界是平的。。。哈维尔。链接未找到=/但我确信这很有趣哈哈