[代码随想录]Day09-栈与队列part01

题目:232. 用栈实现队列

思路:

因为go没有栈和队列的类型,直接自己写就行了。

比较简单的实现,具体看代码中的注释。

代码:

type MyQueue struct {
    numbers []int
}


func Constructor() MyQueue {
    return MyQueue{numbers:[]int{}}
}


func (this *MyQueue) Push(x int)  {
    this.numbers = append(this.numbers, x) // 添加进去
}


func (this *MyQueue) Pop() int {
    recall := this.numbers[0] // 记录第一个元素
    this.numbers = this.numbers[1:] // 删除第一个元素
    return recall // 返回第一个元素
}


func (this *MyQueue) Peek() int {
    return this.numbers[0] // 返回第一个元素
}


func (this *MyQueue) Empty() bool {
    if len(this.numbers) == 0 { // 如果内部的数组长度为0返回true
        return true
    }
    return false
}


/**
 * Your MyQueue object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Peek();
 * param_4 := obj.Empty();
 */

参考:

代码随想录

题目:225. 用队列实现栈

思路:

比较简单的实现,具体看代码中的注释。

直接记录了lens能省一点时间,值得注意的是结构体初始化的时候多个成员的话要在每一个的后面都要加上逗号","包括最后一个。

代码:

type MyStack struct {
    numbers []int
    lens int
}


func Constructor() MyStack {
    return MyStack{
        numbers : []int{},
        lens:0,
    }
}


func (this *MyStack) Push(x int)  {
    this.numbers = append(this.numbers, x) // 压入栈顶
    this.lens++
}


func (this *MyStack) Pop() int {
    recall := this.numbers[this.lens-1]
    this.numbers = this.numbers[:this.lens-1]
    this.lens--
    return recall
}


func (this *MyStack) Top() int {
    return this.numbers[this.lens-1]
}


func (this *MyStack) Empty() bool {
    if this.lens == 0 {
        return true
    }
    return false
}


/**
 * Your MyStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(x);
 * param_2 := obj.Pop();
 * param_3 := obj.Top();
 * param_4 := obj.Empty();
 */

参考:

代码随想录

posted @   WtcSky  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示