剑指 Offer 09. 用两个栈实现队列


title: 剑指 Offer 09. 用两个栈实现队列 tags:

  • 队列 categories:
  • 算法
  • 剑指 Offer

题目描述

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 $appendTail$ 和 $deleteHead$ ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,$deleteHead$ 操作返回 -1 )

示例 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]

示例 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

提示:

  • $1 <= values <= 10000$
  • 最多会对 appendTail、deleteHead 进行 10000 次调用​

算法

(辅助栈) $O(n)$

一个主栈 $stk$ 用于存储队列元素,一个辅助栈 $cache$ 用于暂存中间状态

  1. appendTail(val):直接将 $val$ 压入到 $stk$ 中
  2. deleteHead():先将 $stk$ 中的元素弹到 $cache$ 中,此时 $cache$ 的栈顶就是队列的队头,删除即可。
时间复杂度

$O(n)$

空间复杂度

$O(n)$

C++ 代码
class CQueue {
public:
    stack stk, cache;

    CQueue() {

    }

    void appendTail(int value) {
        stk.push(value);
    }

    int deleteHead() {
        if (stk.empty()) return -1;
        while (stk.size()) cache.push(stk.top()), stk.pop();
        int val = cache.top();
        cache.pop();
        while (cache.size()) stk.push(cache.top()), cache.pop();
        return val;
    }
};

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue* obj = new CQueue();
 * obj->appendTail(value);
 * int param_2 = obj->deleteHead();
 */
Java 代码
class CQueue {
    private Stack stk;
    private Stack cache;

    public CQueue() {
        stk = new Stack<>();
        cache = new Stack<>();
    }

    public void appendTail(int value) {
        stk.push(value);
    }

    public int deleteHead() {
        if (stk.isEmpty()) {
            return -1;
        }
        while (!stk.isEmpty()) {
            cache.push(stk.pop());
        }
        int val = cache.pop();
        while (!cache.isEmpty()) {
            stk.push(cache.pop());
        }
        return val;
    }
}

/**
 * Your CQueue object will be instantiated and called as such:
 * CQueue obj = new CQueue();
 * obj.appendTail(value);
 * int param_2 = obj.deleteHead();
 */
Python 代码
class CQueue:

    def __init__(self):
        self.stk = []
        self.cache = []

    def appendTail(self, value: int) -> None:
        self.stk.append(value)

    def deleteHead(self) -> int:
        if not self.stk:
            return -1
        while self.stk:
            self.cache.append(self.stk.pop())
        val = self.cache.pop()
        while self.cache:
            self.stk.append(self.cache.pop())
        return val

# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

推荐阅读:

  • https://www.mianshi.online
  • https://www.i9code.cn

    本文由博客一文多发平台 OpenWrite 发布!

你可能感兴趣的:(java,面试题,后端)