堆栈实现的弹出操作无法按预期工作

时间:2013-10-28 15:27:14

标签: java algorithm stack

我是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个保留在堆栈中。我能够理解可能出现的问题,但无法在代码中找到它。

2 个答案:

答案 0 :(得分:3)

问题是您要拨打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);

答案 1 :(得分:0)

你要两次打电话。

第一个是:

if(st.pop()==-1)
       System.out.println("The stack is empty.");

,第二个是:

System.out.printf("The element popped is %d\n",st.pop());

您可以使用变量存储st.pop()的值,然后检查变量的值。接下来写一些逻辑代码。

相关问题