跳到主要内容

2023-9-4

9-4

队列

题号232. 用栈实现队列

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

思路 使用两个栈实现,一个入栈,一个出栈


var MyQueue = function() {
this.is = []
this.os = []
};

/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.is.push(x)
};

/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(!this.os.length){
while(this.is.length){
this.os.push(this.is.pop())
}
}
return this.os.pop()
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(!this.os.length){
while(this.is.length){
this.os.push(this.is.pop())
}
}
return this.os[this.os.length-1]
};

/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.os.length&&!this.is.length
};

/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/