栈的pop

栈的弹出函数

/** 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());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章