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