简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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