为什么对于超过 1 个元素的堆栈,我的大小总是 1?

Why is my size always 1 for a stack of more then 1 element?

我的任务是实现一个 MyStack class,它采用给定的 IStack 接口并实现方法。除了尺寸,一切正常。 我的尺寸总是赋值 1。 这是我的大小方法代码。

    public int size() {
        int count = 0;
        if(isEmpty() == true) {
            return 0;
        }
        else {
            while(head.getNext() != null) {
                count++;
                return count;
            }
            return count;
        }
    }

如果我删除 while 语句中的 return 语句,整个过程将不再有效。 那你有什么建议吗?

您需要一些可以更新的变量,以便在迭代时存储当前项。重复调用 head.getNext() 是不够的,因为它永远是第一个元素。

WhateverItemClass current = head.getNext();
while(current != null) {
    count++;
    current = current.getNext();
}
return count;

首先不要在 if 语句中比较布尔值,只需使用:

if(isEmpty())

如果在循环内删除 return 语句时程序没有终止,似乎 getNext() 总是 returning 一个非空值...