232. 用栈实现队列(JS实现)

1 题目

使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false

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

2 思路

这道题思路就是用两个栈来模拟队列,当进行弹出操作时,将一个栈的元素全部弹出,再压入另一个栈,栈顶元素就为最先进入的元素

3代码

var MyQueue = function() {
  this.stack1 = [];
  this.stack2 = [];
};


MyQueue.prototype.push = function(x) {
  this.stack1.push(x);
};


MyQueue.prototype.pop = function() {
  if (this.stack2.length === 0) {
    while (this.stack1.length > 0) {
      this.stack2.push(this.stack1.pop());
    }
  }

  return this.stack2.pop();
};


MyQueue.prototype.peek = function() {
  if (this.stack2.length > 0) {
    return this.stack2[this.stack2.length - 1];
  } else {
    return this.stack1[0];
  }
};


MyQueue.prototype.empty = function() {
  return this.stack1.length === 0 && this.stack2.length === 0;
};

猜你喜欢

转载自blog.csdn.net/zjw_python/article/details/108028563
今日推荐