遍历链表时出现无限循环

3

我正在尝试计算我的链表中特定整数出现的次数。然而,我遇到了无限循环的问题。我尝试打印变量以查看代码到达何处,但没有任何内容打印。我想知道是否有人可以帮忙看看。

我的 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;
}
3个回答

5

即使if条件不满足,您也应将head移至下一个节点。


没看到,谢谢!对我来说已经很晚了! - Liondancer
3
没问题,这就是为什么世界有白天和黑夜的原因 :) 白天的人帮助黑夜的人 ;) - Maroun
1
我曾经认为世界是平的...哈哈 - Liondancer
好的...是这样。 - Maroun
链接未找到 =/ 但我确定它很有趣哈哈 - Liondancer

3

只有在当前节点等于您发送到 countInt 的数字时,才会移动到下一个节点。


1

head = head.next 移出 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接