我的 Stack class 中的 Pop 或 Push 方法是否写错了?

Are my Pop or Push method in my Stack class written incorrectly?

当我尝试对此进行测试时;例如,如果我压入 4 个元素,然后创建一个 for 循环:

for( int i=0; i<=stack.size(); i++){
System.out.println(stack.pop());
}

它不输出最后一个元素。是我的pop方法有问题吗?

 public void push(E element){
    top= new Node<E>(element,top);
    size++;

}

public E pop(){
    E popped;
    if(this.isEmpty()){
        throw new EmptyStackException();
    }
    popped=top.data;
    this.setTop(top.next);
    size--;
    return popped;
    }

问题是您使用大小遍历堆栈。

看看你的 for 循环会发生什么:

  1. 我=0;大小 = 4;我 <= 大小 == 真
  2. 我=1;大小 = 3;我 <= 大小 == 真
  3. 我=2;大小 = 2;我 <= 大小 == 真
  4. 我=3;大小 = 1;我 <= 大小 == 假

所以你不弹出最后一个元素。

但是,与其使用大小为限制的 for 循环,不如实现一个 hasNext() 方法,如果堆栈有下一个元素,则 returns 为真:

while(stack.hasNext())
{
    Element e = stack.pop();
    // Do stuff...
}

或者 pop() returns 如果堆栈上没有更多元素并且您像这样循环遍历它,则为 null:

Element e;
while((e = stack.pop()) != null)
{
    // Do stuff...
}

如果你使用 .pop() 你的变量的大小会少 1,所以如果你在循环结束时省略增量会更好:

for( int i=0; i<=stack.size(); ){
  System.out.println(stack.pop());
}