我是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;
    }
}

此算法的caseinswitch语句如下:
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我能理解可能的错误,但不能在代码中精确指出。

最佳答案

问题是您要调用pop两次(一次在st.pop() == -1中,一次在printf中)。
您应该将代码更改为:

int value = st.pop();
if (value == -1)
   System.out.println("The stack is empty.");
else
   System.out.printf("The element popped is %d\n", value);

09-11 17:35
查看更多