链式队列的实现(Go)

队列结构定义如下:

// 队列结点
type QueNode struct {
    Val interface{}
    Next *QueNode
}


// 链式队列
type LinkedListQueue struct {
    Head *QueNode
    Tail *QueNode
    Length int
}

实现以下操作:

  • 新建队列
  • 元素入队
  • 元素出队
  • 队列判空
  • 队列遍历

代码如下:

package main

import "fmt"

// 队列结点
type QueNode struct {
    Val interface{}
    Next *QueNode
}


// 链式队列
type LinkedListQueue struct {
    Head *QueNode
    Tail *QueNode
    Length int
}

// 新建队列
func NewLinkedListQueue() *LinkedListQueue {
    return &LinkedListQueue{
        Head:   nil,
        Tail:   nil,
        Length: 0,
    }
}


// 入队
func (this LinkedListQueue) EnQueue(v interface{}) {
    node := &QueNode{v, nil}

    if this.Tail == nil {
        this.Tail = node
        this.Head = node
    }else {
        this.Tail.Next = node
        this.Tail = node // 队尾始终指向队尾元素
    }
    this.Length++
}

// 出队
func (this *LinkedListQueue) Dequeue() interface{} {
    if this.Head == nil {
        return nil
    }
    v := this.Head.Val
    this.Head = this.Head.Next
    this.Length--
    return v
}

// 判断队列是否为空
func (this *LinkedListQueue) Empty() bool {
    return this.Tail == nil
}

// 返回队列元素
func (this *LinkedListQueue) String() string {
    if this.Head == nil {
        return "Empty queue!"
    }
    result := "head<-"
    for cur := this.Head; cur != nil; cur = cur.Next {
        result += fmt.Sprintf("<-%+v", cur.Val)
    }
    result += "<-tail"
    return result
}
全部评论

相关推荐

05-13 00:41
已编辑
北京邮电大学 Java
理性的杰克刷牛客:ai肯定要有的,最好学一下agent方向加一个智能客服什么的进去,并且多加点什么skill,mcp啥的,另外你现在的项目深度有些浅,这些功能都太简单了,而且也不是真正能扛高并发的实现,没有什么太大的亮点,可以去网上找点更有深度的项目。可以先投一些中小厂,有实习经历以后再去大厂,你现在这个大厂可能机会不大
点赞 评论 收藏
分享
LuminousZJ:不行,最后还是要看学信网的,这点不能伪装,也骗不过人家,得不偿失
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务