232. Implement Queue using Stacks

232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.

  • pop() -- Removes the element from in front of queue.

  • peek() -- Get the front element.

  • empty() -- Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.

  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.

  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

My Solutions:

需要两个stack才能通过两次压栈变成queue的顺序

1。方法1

未经处理的stack是s,将s pop出再push进q,就变成了正确的q的顺序

pop, peek: O(n);

push, empty: O(1)

class MyQueue {

    Stack<Integer> s, q;
    
    /** Initialize your data structure here. */
    public MyQueue() {
        s = new Stack<>();
        q = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        s.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!q.isEmpty()) {
            return q.pop();
        } else {
            while (!s.isEmpty()) {
                q.push(s.pop());
            }
            return q.pop();
        }    
    }
    
    /** Get the front element. */
    public int peek() {
        if (!q.isEmpty()) {
            return q.peek();
        } else {
            while (!s.isEmpty()) {
                q.push(s.pop());
            }
            return q.peek();
        } 
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return s.isEmpty() && q.isEmpty();
    }
}

2。 方法2

push: O(n);

pop, peek, empty: O(1)

在push进去的时候,多一个temp,用来把stack里pop出的元素的再push回去,让stack的顺序变成queue的顺序

class MyQueue {

    Stack<Integer> q, temp;
    
    /** Initialize your data structure here. */
    public MyQueue() {
        temp = new Stack<>();
        q = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        if (q.isEmpty()) {
            q.push(x);
        }
        else {
            while (!q.isEmpty()) {
                temp.push(q.pop());
            }
            temp.push(x);
            while (!temp.isEmpty()) {
                q.push(temp.pop());
            }
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return q.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return q.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return q.isEmpty();
    }
}

Last updated