简体   繁体   English

迭代链表时无限循环

[英]Infinite loop when iterating through Linked List

I am trying to count the number of time a particular integer occurs within my Linked List. 我试图计算在我的链接列表中发生特定整数的时间。 However I am running into an infinite loop. 但是我遇到了无限循环。 I try to print variables to see where the code reaches but nothing prints. 我尝试打印变量以查看代码到达的位置但没有打印。 I was wondering if someone could be an extra pair of eyes for me. 我想知道是否有人可以为我增加一双眼睛。

My LinkedListNode class is simply: 我的LinkedListNode类很简单:

public class LinkedListNode {
    int data;
    public LinkedListNode next;


    // constructor
    public LinkedListNode(int newData) {
        this.next = null;
        this.data = newData;
    }
}

My code: 我的代码:

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的数字时,您只能移动到下一个节点。

Moving head = head.next out of the while loop will help with the infinite loop, but you would want to check the head for null, not head.next, so the while loop will check the value of the last element 从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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM