[Leetcode] Implement Queue using Stacks 用栈实现队列

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).

双栈法

复杂度

时间 入队O(1) 出队O(N) 空间 O(N)

思路

队列和栈都是顺序插入的,区别在于队列的出口方向和栈的出口方向是相反的,利用这个性质,如果我们将元素按照顺序插入栈后,再一个个弹出并反向插入另一个栈,那么这第二个栈的出口顺序就和队列是一样的了。所以我们构造两个栈,所有新加的元素都加入输入栈,一旦要出队列时,我们便将输入栈的元素都反向加入输出栈,再输出。需要注意的是,如果输出栈不为空时,说明当前要输出的元素还在输出栈中,所以我们就暂时不用将输入栈的元素加入输出栈(而且加入后也会导致顺序错误)。

注意

Leetcode的方法是pop和push,实际上我们应该实现的是poll和offer(或者enqueue和dequeue),offer的实现和push是一样的,但将pop改为poll时,我们要先把peek到的元素保存,然后再弹出输出栈,然后返回这个保存的元素。

代码

class MyQueue {
    
    Stack<Integer> input = new Stack<Integer>();
    Stack<Integer> output = new Stack<Integer>();
    
    // 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() {
        int x = peek();
        output.pop();
    }

    // Get the front element.
    public int peek() {
        if(output.isEmpty()){
            while(!input.isEmpty()){
                output.push(input.pop());
            } 
        }
        return output.peek();
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return input.isEmpty() && output.isEmpty();
    }
}
    原文作者:ethannnli
    原文地址: https://segmentfault.com/a/1190000003738849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞