我是JAVA n00b。我正試圖在Java中實現一個堆棧數據結構。 push,peek和display的算法工作正常。該pop
算法不按預期工作:堆棧實現的彈出操作未按預期工作
public int pop() {
int temp;
if(isEmpty())
return -1;
else {
temp = arr[topElem];
topElem--; // points to the top most element in the stack
count--; // keeps track of the total number of elements in the stack
return temp;
}
}
的case
在switch
聲明此算法如下: -
case 2:
if(st.pop()==-1)
System.out.println("The stack is empty.");
else
System.out.printf("The element popped is %d\n",st.pop());
break;
如果輸入的元素是(按順序): - 1 2 4 然後在第一次調用pop
時,彈出2,然後只有1保留在堆棧中。我能夠理解什麼可能是錯誤的,但無法在代碼中找到它。
返回'-1'指示堆棧爲空不是好主意,如果要將int'-1'放在堆棧上怎麼辦?在一個空棧上調用'pop()'更好地拋出Exception。 – MrSmith42
你叫兩次彈出! –