3

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

3 Answers 3

5

You should move head to the next node even if the if doesn't satisfy.

Sign up to request clarification or add additional context in comments.

5 Comments

did not see this thanks! it's late in the night for me!
@Liondancer No problem, that's why there's a day and night in the world :) People in day help people in night ;)
I thought the world was flat... haha
Well.. it is.
linked not found =/ but im sure it was funny haha
3

You only move to the next node when the current node is equal to the number you send to countInt.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.