如何检查堆栈是否为空

时间:2015-07-20 13:15:29

标签: java stack

这是我的数组与我的主要分开 我只有一个问题,我的代码没有问题,但缺乏 如果我运行pop但堆栈是空的,它必须有一个对话框说它是空的,我尝试了一个if else语句但我不知道在哪里放它或者它真的是if else语句需要,反正在这里&#我的代码。 。

public class ArrayStack {
        int STACK_MAX = 20;
        int size = -1 ;
        int top = -1 ;
        int StackObj[] = new int[STACK_MAX];

          /**************** for PUSH METHOD *********/

        public void Push(int obj) {
            if (size()==STACK_MAX){
                System.out.println("STACK is FULL");
                }
            else{
                    StackObj[++top]= obj;
                }
        } 

        /**************** for SIZE Method ********/

        public int size() {
            return (top+1);    
        }

      /******************** for Display Method****/

        public void DisplayStack() {
                String disp="";

                for (int i=top; i>=0; i--){
                    disp += StackObj[i] + "\n";                     
                }
              JOptionPane.showMessageDialog(null, "Elements of the Stacks : \n" + disp);
            }

      /***************** for isEmpty Method *******/

      public boolean isEmpty(){

        return (top == -1);

      }

      /***************** for Top Method ***********/
        public int Topmethod(){

        int taas = StackObj[top];

        JOptionPane.showMessageDialog(null,"Top is : "+taas);
        return (top);
        }

      /***************** for Pop Method ***********/       
           public int pop(){

            int topItem = StackObj[top];
               top--;
            JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
          return(top);
        } 
    }

2 个答案:

答案 0 :(得分:0)

您可能希望在pop方法中添加一些内容来处理堆栈为空时的识别,然后处理空堆栈的情况,例如:

public int pop(){
    if(size() == 0){  //detect empty stack
        JFrame frame = new JFrame("my frame");; //handle empty stack
        JOptionPane.showMessageDialog(frame,"Stack is empty!");
        return null; //make sure you handle a null return value if you use this
    }
    int topItem = StackObj[top];
       top--;
    JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
  return(top);


} 

答案 1 :(得分:0)

这里我编辑了

public int pop(){
    if(size() == 0){  //detect empty stack
    JOptionPane.showMessageDialog(null,"Stack is empty!");
    return (top); //make sure you handle a null return value if you use this
}
    int topItem = StackObj[top];
       top--;
    JOptionPane.showMessageDialog(null,"The recently pushed number was Deleted: "+topItem);
  return(top);


}