Two Stacks Java Solution


  • 0
    A

    class MyQueue {

    Stack<Integer> input;
    Stack<Integer> output;
    
    public MyQueue() {
        input = new Stack<>();
        output = new Stack<>();
    }
    
    private void adjust() {
        if(output.isEmpty()) {
            while(!input.isEmpty()) {
                output.push(input.pop());
            }
        }
    }
    
    // Push element x to the back of queue.
    public void push(int x) {
        input.push(x);
    }
    
    // Removes the element from in front of queue.
    public void pop() {
        adjust();
        if(!output.isEmpty()) {
            output.pop();
        }
    }
    
    // Get the front element.
    public int peek() {
        adjust();
        int temp = -1;
        if(!output.isEmpty()) {
            temp = output.peek();
        }
        return temp;
    }
    
    // Return whether the queue is empty.
    public boolean empty() {
        return input.size() == 0 && output.size() == 0;
    }
    

    }


Log in to reply
 

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