Implement Queue using Stacks

Link: https://leetcode.com/problems/implement-queue-using-stacks/

Constaints


    1 <= x <= 9
    At most 100 calls will be made to push, pop, peek, and empty.
    All the calls to pop and peek are valid.

Idea

Use one stack for pushing element, the other stack for poping element. When peek/pop an elements, if the output stack is empty, shift all elements from input stack to output stack first.

Code

class MyQueue {
    Stack<Integer> in;
    Stack<Integer> out;
    
    /** Initialize your data structure here. */
    public MyQueue() {
        in = new Stack<>();
        out = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        moveAllToOut();
        return out.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        moveAllToOut();
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
    
    private void moveAllToOut() {
        if (!out.isEmpty()) {
            return;
        }
        
        while (!in.isEmpty()) {
            out.push(in.pop());
        }
    }
}
  • Time: push() and empty() is O(1). peek() and pop() are amortized O(1). Assuming all the calls are valid, there are at most N pop() calls. All elements get moved from input stack to output stack only once, regardless the order of operations.
  • Space: O(n) as we need to store all the elements in stacks.

Similar problem:

Reference: https://leetcode.com/problems/implement-queue-using-stacks/discuss/64206/short-o1-amortized-c-java-ruby

posted on 2021-08-07 00:08  blackraven25  阅读(34)  评论(0)    收藏  举报