一、题目
二、示例
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
三、思路
本题可以使用双栈来解决问题。
四、代码
var MyQueue = function() {
this.stack = []
this._stack = []
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stack.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
while(this.stack.length > 1) {
this._stack.push(this.stack.pop())
}
let cur = this.stack.pop()
while(this._stack.length > 0) {
this.stack.push(this._stack.pop())
}
return cur
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
return this.stack[0]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stack.length > 0 ? false: true
};
/**
* 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()
*/
五、总结
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47450807/article/details/123557235
内容来源于网络,如有侵权,请联系作者删除!