栈数组实现,返回数组大小

stack array implementation, returning size of array

我正在尝试查找堆栈中元素的数量(我正在实现一个数组)。到目前为止我有

   int size = 0;
   while( top != -1 ){
   size++;
   pop();
}
   return size;

}

通过给我大小,这非常有效,但是我不想清空我的数组。我该如何修复我的代码才能执行此操作?

我不确定我是否正确理解了你的问题,但如果你想知道你在一个集合中有多少对象,你可以例如:

for(int i=0; i=<theNameOfYourArray.size(); i++){
    System.out.println("Size of collection currently is: " + i);
}

然后检查 i 的最后一个值的输出。

我将根据我的理解建议以下方法。 不要只是删除 pop() 方法中的最顶层元素,只需减少指向堆栈最顶层元素的指针的值即可。

private int pointerToTheTopmostElement = 0; // increase when pushed, decrease when poped

public int pop(){
    int popingElement = pointerToTheTopmostElement;
    pointerToTheTopmostElement--;
    return stack[popingElement];
}

像这样的东西可能会满足您的需要。