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

原题链接: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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值