Eddie Rukmanis
Eddie Rukmanis

Reputation: 37

How to properly count nodes in the stack?

I created this loop to count elements in the stack that are within the interval [-10;10], but when I return the answer, I can see, that it doesn't count the last node, is there something wrong here?

    public int intervalNumbers() {

        int counter = 0;
        Node node;
        for (node = top;
             node.link != null;
             node = node.link) {
            if (node.data >= -10 && node.data <= 10) {
                counter++;
            }
        }
        return counter;
    } 

Upvotes: 1

Views: 75

Answers (1)

Thiyagu
Thiyagu

Reputation: 17900

It is sort of off by one case.

for (node = top;
         node.link != null;
         node = node.link)

Because of the condition node.link != null, the body of the loop is not executed for the last node (as the last node's link would be null)

Change it to node != null

Upvotes: 2

Related Questions