算法列表

232.用栈实现队列 简单

布莱克2026-03-10 16:00队列

问题:

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:

  • 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

回答:

这道题可以理解用栈实现队列的操作,正常push,可队列是从队列的头部弹出元素,比如shift()方法,但是对于栈只有pop(),从队尾弹出

但是不可以直接使用shift(),相当于用栈的方法来模拟

var MyQueue = function() {
    this.stackIn = [];
    this.stackOut = [];
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    this.stackIn.push(x);
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    if (!this.stackOut.length) {
        while(this.stackIn.length) {
            this.stackOut.push(this.stackIn.pop())
        }
    }
    return this.stackOut.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    if (!this.stackOut.length) {
        while(this.stackIn.length) {
            this.stackOut.push(this.stackIn.pop())
        }
    }
    return this.stackOut[this.stackOut.length - 1];
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    return this.stackOut.length == 0 && this.stackIn.length == 0
};


assistant