Search code examples
javaoopcollectionsqueuestack

Receiving a error saying that stack is empty in java leetcode


The code for the same is here

class MyQueue {

Stack<Integer> mainS;
Stack<Integer> helperS;
 // Stack<Integer> mainS =new Stack<>();
 // Stack<Integer> helperS =new Stack<>();

public MyQueue() {
      mainS =new Stack<>();
      helperS =new Stack<>();
}

public void push(int x) {
    if(mainS.size()>0){
         mainS.push(x);
    }
   
}

public int pop() {
    while(mainS.size() >1){
        helperS.push((mainS.pop()));
    }
    int val = mainS.pop();

    mainS.add(helperS.pop());

    return val;
}

public int peek() {
    while(mainS.size() >1){
        helperS.push((mainS.pop()));
    }
    int val1 = mainS.pop();
    helperS.push(val1);

    mainS.add(helperS.pop());

    return val1;
}

public boolean empty() {
    if(mainS.size()==0) return true;
    return false;
}

}

/**

  • Your MyQueue object will be instantiated and called as such:
  • MyQueue obj = new MyQueue();
  • obj.push(x);
  • int param_2 = obj.pop();
  • int param_3 = obj.peek();
  • boolean param_4 = obj.empty(); */

The error coming is that *java.util.EmptyStackException

at line 102, java.base/java.util.Stack.peek

at line 84, java.base/java.util.Stack.pop

at line 35, MyQueue.peek

at line 69, Driver.helperSelectMethod

at line 89, Driver.helper

at line 110, Driver.main*

The Logic is correct Please help someone.


Solution

  • Replace the below code

     public void push(int x) {
        if(mainS.size()>0){
             mainS.push(x);
        }
      }
    

    with

        public void push(int x) {
             mainS.push(x);
       }
    

    You are checking the size of the stack should be greater than 0 before you are pushing. But it will be 0 when you create it and you will never push if it's 0 so it will always be empty.