栈的pop

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42568655/article/details/90752546

栈的弹出函数

/** Return the number of elements in the stack */
public int getSize() {
	return size;
}

/** Return and remove the top element from the stack */
public int pop() {
	return elements[--size];
}

使用弹出的时候错误

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

原因是,每次弹出一个元素后栈的长度就减少一。所以这样会让栈弹出的数量变少。因此先记录下栈的长度(深度),然后在进行遍历弹出。修改后如下

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

猜你喜欢

转载自blog.csdn.net/weixin_42568655/article/details/90752546
pop