Java accepted code


  • 0
    X
    class MyQueue {
    
    int size;
    Stack<Integer> pushStack;
    Stack<Integer> popStack;
    
    public MyQueue(){
        size=0;
        pushStack=new Stack<>();
        popStack=new Stack<>();
    }
    
    // Push element x to the back of queue.
    public void push(int x) {
        pushStack.push(x);
        size++;
    }
    
    // Removes the element from in front of queue.
    public void pop() {
        if(popStack.isEmpty()){
            inflatePopStack();
        }
        popStack.pop();
        size--;
    }
    
    private void inflatePopStack(){
            int count=0;
            Stack<Integer> temp=new Stack<>();
            while(count<size){
                int num=pushStack.pop();
                popStack.push(num);
                temp.push(num);
                count++;
            }
            while(!pushStack.isEmpty()){
                pushStack.pop();
            }
            while(!temp.isEmpty()){
                pushStack.push(temp.pop());
            }
    }
    
    // Get the front element.
    public int peek() {
        if(popStack.isEmpty()){
            inflatePopStack();
        }
        return popStack.peek();
    }
    
    // Return whether the queue is empty.
    public boolean empty() {
        return size==0;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.