Java 堆栈实现的Pop操作未按预期工作

Java 堆栈实现的Pop操作未按预期工作,java,algorithm,stack,Java,Algorithm,Stack,我是JavaN00B。我试图用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

我是JavaN00B。我试图用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;
    }
}
此算法的
switch
语句中的
case
如下所示:-

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);

问题是您调用了两次
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);

问题是您调用了两次
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);

问题是您调用了两次
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);

你给爸爸打了两次电话

第一个是:

if(st.pop()==-1)
       System.out.println("The stack is empty.");
第二个是:

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

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

你给pop打了两次电话

第一个是:

if(st.pop()==-1)
       System.out.println("The stack is empty.");
第二个是:

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

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

你给pop打了两次电话

第一个是:

if(st.pop()==-1)
       System.out.println("The stack is empty.");
第二个是:

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

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

你给pop打了两次电话

第一个是:

if(st.pop()==-1)
       System.out.println("The stack is empty.");
第二个是:

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

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

我认为这可能是个问题,但我没有信心真正尝试一下。ThanksI认为这可能是一个问题,但没有信心实际尝试。ThanksI认为这可能是一个问题,但没有信心实际尝试。ThanksI认为这可能是一个问题,但没有信心实际尝试。感谢返回
-1
作为堆栈为空的指示器不是一个好主意,如果要将int
-1
放在堆栈上怎么办?最好抛出一个异常,
pop()
在空堆栈上被调用。你调用了两次pop!返回
-1
作为堆栈为空的指示符不是好主意,如果要将int
-1
放在堆栈上怎么办?最好抛出一个异常,
pop()
在空堆栈上被调用。你调用了两次pop!返回
-1
作为堆栈为空的指示符不是好主意,如果要将int
-1
放在堆栈上怎么办?最好抛出一个异常,
pop()
在空堆栈上被调用。你调用了两次pop!返回
-1
作为堆栈为空的指示符不是好主意,如果要将int
-1
放在堆栈上怎么办?最好抛出一个异常,
pop()
在空堆栈上被调用。你调用了两次pop!