Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chencl1986 opened this issue Sep 7, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/implement-stack-using-queues/

解题思路:

参考了官方题解的方法二 (两个队列, 压入 - 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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant