30. 用栈实现队列&用队列实现栈【LC232&225】

74 阅读2分钟

题目:

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

实现 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(双端队列)来模拟一个栈,只要是标准的栈操作即可。

核心思路:

用两个栈可以模拟队列操作,也就是FILO + FILO = FIFO

解:

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

function in2out(inList, outList) {
  while (inList.length) {
    outList.push(inList.pop())
  }
}

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

/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {

  if (!this.outStack.length) {
    in2out(this.inStack, this.outStack);
  }
  return this.outStack.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
  if (!this.outStack.length) {
    in2out(this.inStack, this.outStack);
  }
  return this.outStack[this.outStack.length - 1]
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
  return !(this.inStack.length || this.outStack.length)

};

延伸思考:

怎样用队列实现栈呢?

首先想到的思路是,用两个队列来实现

push,即正常向queue1中push即可;

pop&peek,用一个辅助队列,将当前队列所有的内容进行pop并push入辅助队列,直到当前队列剩余最后一下,pop出来不再加入辅助队列,即可正常抛出;

然后将当前队列重新指向辅助队列,即可完成。

/**
 * Initialize your data structure here.
 */
var MyStack = function() {
    this.queue = [];
    this.size = 0;
};

/**
 * Push element x onto stack. 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function(x) {
    this.queue.push(x);
    this.size++;
};

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function() {
    const tempQueue = [];
    // 暂时保存队列的前n-1个元素
    for(let i = 0; i < this.size - 1; i++) {
        tempQueue.push(this.queue.shift());
    }
    // 取出最晚进入队列的第n个元素,原队列已空,新队列剩下n-1个元素
    const val = this.queue.shift();
    this.queue = tempQueue;
    this.size--;
    return val;
};

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function() {
    const tempQueue = [];
    for(let i = 0; i < this.size - 1; i++) {
        tempQueue.push(this.queue.shift());
    }
    const val = this.queue.shift();
    this.queue = tempQueue;
    this.queue.push(val);
    return val;
};

/**
 * Returns whether the stack is empty.
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
    return !this.size;
};