Day2-用栈实现队列

YVTU

🔗 LeetCode 232 - Implement Queue using Stacks

📌 题目描述:

使用两个栈 stackIn 和 stackOut 实现一个队列,支持以下操作:

  • push(x):将元素 x 推到队列的末尾
  • pop():移除队列开头的元素并返回
  • peek():返回队列开头的元素
  • empty():返回队列是否为空

要求:
只能使用栈的标准操作(push, pop, peek, empty)


💡 解题思路:

  • 入队操作(push)直接往 stackIn 中加元素;
  • 出队操作(pop 或 peek)时,如果 stackOut 为空,则将 stackIn 中的所有元素倒序转移到 stackOut;
  • 保证先进先出(FIFO)的顺序。

✅ JavaScript 实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var MyQueue = function () {
this.stackIn = [];
this.stackOut = [];
};

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

MyQueue.prototype.pop = function () {
if (this.stackOut.length === 0) {
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop());
}
}
return this.stackOut.pop();
};

MyQueue.prototype.peek = function () {
if (this.stackOut.length === 0) {
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop());
}
}
return this.stackOut[this.stackOut.length - 1];
};

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

🧠 思考拓展:

  • 如果反过来是“用队列实现栈”应该怎么做?👉 LeetCode 225
  • 队列相关拓展题:滑动窗口最大值、最小栈等