leetcode 题号232 用栈实现队列

2019-06-09  本文已影响0人  Cloneable

查看题目详情可点击此处来源:力扣(LeetCode)」。

题目

使用栈实现队列的下列操作:

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

说明:

解题思路

此题解题思路与使用队列实现栈的相似,同样需要两个栈,一个栈作为「临时栈」,负责数据入队时临时存放,另一个栈作为「队列栈」用来模拟队列。

当进行 poppeekempty 的队列操作时,都可以使用队列栈的 poppeekempty 的栈操作。在入队操作时,需要将入队数据暂存在临时栈中(临时栈永远为空),再将队列栈的数据按入栈顺序依次转移至临时栈中,接着临时栈与队列栈引用交换,交换完成后将临时栈清空。

代码实现

class MyQueue {

    private Stack<Integer> tempStack;
    private Stack<Integer> stackQueue;

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

    /** Push element x to the back of queue. */
    public void push(int x) {
        if(stackQueue.empty()) {
            stackQueue.push(x);
        } else {
            tempStack.push(x);
            tempStack.addAll(stackQueue);

            Stack<Integer> temp = stackQueue;
            stackQueue = tempStack;
            tempStack = temp;
            tempStack.clear();
        }
    }

    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(stackQueue.empty()) {return 0;}

        return stackQueue.pop();
    }

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

    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stackQueue.empty();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读