JS用两个栈实现一个队列

题目:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾
  • int pop() 从队列的开头移除并返回元素
  • int peek() 返回队列开头的元素
  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

思路:一个作为存储栈,另一个作为辅助栈

入队(push)

一个队列是 FIFO 的,但一个栈是 LIFO 的。这就意味着最新压入的元素必须得放在栈底。为了实现这个目的,我们首先需要把 s1 中所有的元素移到 s2 中,接着把新元素压入 s2。最后把 s2 中所有的元素弹出,再把弹出的元素压入 s1。

出队(pop)

直接从 s1 弹出就可以了,因为 s1 的栈顶元素就是队列的队首元素。同时我们把弹出之后 s1 的栈顶元素赋值给代表队首元素的 front 变量。

判断空(empty)

s1 存储了队列所有的元素,所以只需要检查 s1 的是否为空就可以了。

取队首元素(peek)

在我们的算法中,用了 front 变量来存储队首元素,在每次 入队 操作或者 出队 操作之后这个变量都会随之更新。

完整代码

var MyQueue = function() {
  this.stack = [];
  this.helpStack = [];
};

MyQueue.prototype.push = function(x) {
  while(this.stack.length !== 0){
    this.helpStack.push(this.stack.pop());
  }
  this.helpStack.push(x);
  while(this.helpStack.length !== 0){
    this.stack.push(this.helpStack.pop());
  }
};

MyQueue.prototype.pop = function() {
  return this.stack.pop();
};

MyQueue.prototype.peek = function() {
  return this.stack[this.stack.length - 1];
};

MyQueue.prototype.empty = function() {
  return this.stack.length === 0;
};

猜你喜欢

转载自blog.csdn.net/weixin_43804496/article/details/115284776