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题解:232. 用栈实现队列,使用两个栈 入队 - O(n), 出队 - O(1),JavaScript,详细注释 #160

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

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/

解题思路:

参考了官方题解中的方法一(使用两个栈 入队 - O(n)O(n), 出队 - O(1)O(1))。

  1. 入队时,将s1的元素倒过来存入s2。
  2. 再将入队元素存在s2的栈顶,这样s2中的元素顺序就与入队顺序相同。
  3. 最后将s2元素再倒过来存入s1,这样s1中元素的顺序与入队顺序相反,此时进行出栈操作的元素就与出队操作相同。
/**
 * Initialize your data structure here.
 */
var MyQueue = function () {
  this.s1 = []; // 缓存队列
  this.s2 = []; // 入队时缓存s1
};

/**
 * Push element x to the back of queue.
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
  // 将s1中元素缓存到s2
  while (this.s1.length) {
    this.s2.push(this.s1.pop());
  }

  // 入队元素缓存到s2的栈顶,
  this.s2.push(x);

  // 将s2元素存回s1,新入队的元素变为栈底,栈顶则是队首元素
  while (this.s2.length) {
    this.s1.push(this.s2.pop());
  }
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function () {
  return this.s1.pop();
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function () {
  return this.s1[this.s1.length - 1];
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
  return !this.s1.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