# 232. 用栈实现队列
请你仅使用两个栈实现先入先出队列。
# 解题思路
var MyQueue = function () {
this.stack1 = [] // support push() and pop()
this.stack2 = []
}
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
if (this.stack2.length) {
while (this.stack2.length) {
this.stack1.push(this.stack2.pop())
}
}
this.stack1.push(x)
}
/**
* @return {number}
*/
MyQueue.prototype.pop = function () {
if (this.stack1.length) {
this.stack2.length = 0
// equal to call empty()
while (this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
}
const v = this.stack2.pop()
return v
}
/**
* @return {number}
*/
MyQueue.prototype.peek = function () {
if (this.stack1.length) {
this.stack2.length = 0
while (this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
}
// equal to call peek()
return this.stack2[this.stack2.length - 1]
}
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !(this.stack1.length || this.stack2.length)
}
# 参考
← 队列 239. 滑动窗口最大值 →