代码随想录算法训练营第第十天 | 232.用栈实现队列 、225. 用队列实现栈
232.用栈实现队列
题目链接/文章讲解/视频讲解:https://programmercarl.com/0232.用栈实现队列.html
var MyQueue = function() {
this.stackIn = [];
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stackIn.push(x);
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(this.stackOut.length>0){
return this.stackOut.pop();
}
while(this.stackIn.length>0){
this.stackOut.push(this.stackIn.pop());
}
return this.stackOut.pop();
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
let res = this.pop();
this.stackOut.push(res);
return res;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
if (this.stackOut.length ===0 && this.stackIn.length===0) {
return true;
}
return false;
};
/**
* 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://programmercarl.com/0225.用队列实现栈.html
用一个队列实现比较简单
var MyStack = function() {
this.queue1 = [];
this.queue2 = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue1.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
if (this.queue1.length===0) {
[this.queue1, this.queue2] = [this.queue2, this.queue1];
}
while(this.queue1.length>1){
this.queue2.push(this.queue1.shift());
}
return this.queue1.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let res = this.pop();
this.push(res);
return res;
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !(this.queue1.length || this.queue2.length);
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步