用队列实现栈

86 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情

用队列实现栈

描述

提供给你两个队列,要实现一个先入后出的栈(FILO),并支持普通栈的4中操作:

  1. push(x):将元素x压入栈顶
  2. empty():判断栈是否为空,为空则返回true,否则返回false
  3. top():返回栈顶元素
  4. pop():返回栈顶元素,并删除

分析

这里用两个队列来实现栈,与之前用两个栈来实现队列的总体思路相同,只是里面的具体对元素的操作又是一个相反的过程:一个操作队首元素来实现栈的栈顶操作,另一个是只能操作栈顶来实现队列的头部元素方法。

队列的特点是先进先出(FIFO),队首操作出的元素,队尾可以入操作。栈正好相反,只能操作栈顶元素。

判断栈是否为空,我们直接根据栈的长度。

push方法是将元素压入栈顶,可以直接执行队列的入操作。

top和pop方法两者很类似,相同的是top仅返回栈顶元素,而pop方法不仅返回栈顶元素,而且要删除它,比top多了一步操作。这里要根据队列的特点方法来操作,队列操作出队列只能在队首,而top和pop方法的栈顶元素都在栈顶,也就是相当于在队列的尾部,不能直接返回,队列的尾部只能进行入操作。

程序实现

根据上述分析,具体实现如下:

var MyStack = function() {
  // 初始化两个队列:队列的特点是先进先出
  this.q1 = []
  this.q2 = []
  this.isRemoveTop = function (remove = true) {
    let top
    while (this.q1.length) {
      // 最后一个元素特殊处理
      if (this.q1.length === 1) {
        // shift方法弹出第一个元素并删除
        top = this.q1.shift()
        if (!remove) {
          this.q2.push(top)
        }
      } else {
        this.q2.push(this.q1.shift())
      }
    }
    // 把q2的元素通过队首操作放入队列中
    while (this.q2.length) {
      this.q1.push(this.q2.shift())
    }
    return top
  }
};

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

/**
 * @return {number}
 */
MyStack.prototype.pop = function() {
  return this.isRemoveTop()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function() {
  return this.isRemoveTop(false)
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function() {
  return !this.q1.length
};