美文网首页Leetcode每日两题
Leetcode 232. Implement Queue us

Leetcode 232. Implement Queue us

作者: ShutLove | 来源:发表于2018-02-07 19:54 被阅读7次

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.

题意:用栈来实现队列。

思路:用一个栈来存放push进的元素,另一个栈存放要pop出的元素。当调用pop或peek时,如果pop栈是空的,就把push栈里的元素从栈顶一个个取出来push进pop栈,这样pop栈的栈顶就是最早push进来的元素。

class MyQueue {

    private Stack<Integer> pushStack;
    private Stack<Integer> popStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        this.pushStack = new Stack<>();
        this.popStack = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        this.pushStack.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        this.reloadPop();
        return this.popStack.pop();
    }

    /** Get the front element. */
    public int peek() {
        this.reloadPop();
        return this.popStack.peek();
    }

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return this.pushStack.empty() && this.popStack.empty();
    }

    private void reloadPop() {
        if (this.popStack.size() == 0) {
            while (this.pushStack.size() > 0) {
                this.popStack.push(this.pushStack.pop());
            }
        }
    }
}

相关文章

网友评论

    本文标题:Leetcode 232. Implement Queue us

    本文链接:https://www.haomeiwen.com/subject/chiazxtx.html