LeetCode题解:225. 用队列实现栈,两个队列, 压入 - O(n), 弹出 - O(1),JavaScript,详细注释

164 阅读1分钟

原题链接:leetcode-cn.com/problems/im…

解题思路:

参考了官方题解的方法二 (两个队列, 压入 - O(n)O(n), 弹出 - O(1)O(1))。

在入栈时将队列的元素按照出栈的顺序排列好,在出栈时就可以按顺序出栈。

  1. 使用两个对列,q1用来存储栈,q2保持为空。
  2. 每次入栈时都将q1中的元素存入q2,然后把q1元素都移入q2,q2中元素的排列顺序与入栈顺序相反,之后把q1和q2对调。
  3. 入栈结束后,q1就按照栈的顺序保存了所有元素,出栈时即为后入先出。
/**
 * Initialize your data structure here.
 */
var MyStack = function () {
  this.q1 = []; // 用于存储栈
  this.q2 = []; // 用于存储入栈元素,且保证栈的顺序
};

/**
 * Push element x onto stack.
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
  // 每个入栈元素存储在q2,以保证其是第一个元素,也就是会第一个pop
  this.q2.push(x);

  // 把q1的元素依次移入q2,实现了出栈顺序
  while (this.q1.length) {
    this.q2.push(this.q1.shift());
  }

  // 将q1和q2对调,保证每次出入栈操作的对列一致
  const temp = this.q1;
  this.q1 = this.q2;
  this.q2 = temp;
};

/**
 * Removes the element on top of the stack and returns that element.
 * @return {number}
 */
MyStack.prototype.pop = function () {
  return this.q1.shift();
};

/**
 * Get the top element.
 * @return {number}
 */
MyStack.prototype.top = function () {
  return this.q1[0];
};

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