算法空间/Leetcode/两个栈实现队列

来自康健生活
Kangkk​(留言 | 贡献)2026年1月26日 (一) 03:51的版本 (Kangkk移动页面算法空间/两个栈实现队列至算法空间/Leetcode/两个栈实现队列,不留重定向)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

题目描述

用两个栈实现队列,完成队列的 push 和 pop 功能。

const Queue = function () {
    this.inStack = [];
    this.outStack = [];
}
Queue.prototype.push = function (_v) {
    this.inStack.push(_v);
}
Queue.prototype.pop = function (_v) {
    const {inStack, outStack} = this;
    if (outStack.length) return outStack.pop();
    else {
        while (inStack.length) {
            outStack.push(inStack.pop());
        }
        return outStack.pop() || -1;
    }
}
//
const foo = new Queue();