232. 用栈实现队列

解题思路

  1. enStackoutStack 两个栈实现队列,队列是先进先出,栈是后进先出;

  2. push 方法将数据放到 enStack 中,enStack 用来存储数据;

  3. pop 方法:

    • 先将 enStack 中的数据依次 pop 出来,放入 outStack 中,此时 outStack 的出栈顺序和队列的出队顺序一致;
    • 然后将 outStack 栈顶元素 pop 出去,模拟出队;
    • 最后将 outStack 中的数据依次 pop 出来,放入 enStack 中;

图解

复杂度

  1. 时间复杂度:O(n)

  2. 空间复杂度:O(n)

代码实现

var MyQueue = function () {
    this.enStack = [];
    this.outStack = [];
};

MyQueue.prototype.push = function (x) {
    this.enStack.push(x);
};

MyQueue.prototype.pop = function () {
    // 1. 将 enStack 中的数据依次 pop 出来,放入 outStack 中
    while (this.enStack.length) this.outStack.push(this.enStack.pop());

    // 2. 将 outStack 栈顶元素 pop 出去
    const top = this.outStack.pop();

    // 3. 将 outStack 中的数据依次 pop 出来,放入 enStack 中
    while (this.outStack.length) this.enStack.push(this.outStack.pop());

    return top;
};

MyQueue.prototype.peek = function () {
    return this.enStack[0];
};

MyQueue.prototype.empty = function () {
    return this.enStack.length === 0;
};
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1.
    1. 1.1. 解题思路
    2. 1.2. 图解
    3. 1.3. 复杂度
    4. 1.4. 代码实现