代码随想录算法训练营第十天 | ● 理论基础 ● 232.用栈实现队列 ● 225. 用队列实现栈
今日学习的文章链接和视频链接
● 232.用栈实现队列
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){
return this.stackOut.pop()
}
console.log(this)
while(this.stackIn.length){
this.stackOut.push(this.stackIn.pop())
}
// console.log(this)
return this.stackOut.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
console.log(this)
let temp = this.pop();
// console.log(temp)
this.stackOut.push(temp);
return temp
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
// console.log(this.stackIn.length,this.stackOut.length)
return !this.stackIn.length&&!this.stackOut.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()
*/
● 225. 用队列实现栈
var MyStack = function() {
this.stackIn = [];
this.stackOut = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.stackIn.push(x)
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
if(!this.stackIn.length){
[this.stackIn,this.stackOut] = [this.stackOut , this.stackIn];
}
while(this.stackIn.length>1){
this.stackOut.push(this.stackIn.shift());
}
return this.stackIn.shift()
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let temp = this.pop();
this.stackOut.push(temp);
return temp
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.stackIn.length&&!this.stackOut.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()
*/
今日收获,记录一下自己的学习时长
1h
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?