Go: SingleLinkedList 单向链表
package main import ( "fmt" ) type node struct { id int name string next *node // Node会造成循环引用 } type SingleLinkedList struct { head *node // head!=nil 要进行与nil比较, struct zero value不能为nil length int } // Append 尾部追加 func (list *SingleLinkedList) Append(id int, name string) { head := list.head if head == nil { // 没有任何元素 list.head = &node{ // 对原list操作 id: id, name: name, } list.length++ return } for { if head.next == nil { // 最后一个node break } head = head.next } fmt.Printf("head.next:%v\n", head) head.next = &node{ id: id, name: name, } list.length++ } // Insert 根据id升序插入 func (list *SingleLinkedList) Insert(id int, name string) { head := list.head if head == nil { // SingleLinkedList为空 list.Append(id, name) return } var prev *node for { if head.id > id { // 插入到head前 item := &node{ id: id, name: name, } if head == list.head { // 插入到第一个 list.head = item item.next = head list.length++ return } prev.next = item item.next = head list.length++ return } else if id == head.id { fmt.Printf("id %d exists\n", id) return } prev = head head = head.next if head.next == nil { list.Append(id, name) return } } } // Delete 根据id删除node func (list *SingleLinkedList) Delete(id int) { head := list.head var prev *node if head == nil { fmt.Println("list is empty") } for { if id == head.id { if head == list.head { list.head = list.head.next head.next = nil list.length-- return } prev.next = head.next head.next = nil list.length-- return } prev = head head = head.next if head == nil { fmt.Printf("id %d not exist\n", id) } } } // Show 显示单向链表 func (list *SingleLinkedList) Show() { head := list.head if head == nil { fmt.Println("empty SingleLinkedList") return } fmt.Printf("length: %d\n", list.length) for { fmt.Printf("%d %s\n", head.id, head.name) head = head.next if head == nil { break } } } func main() { list := &SingleLinkedList{} list.Append(11, "aa") list.Append(22, "bb") list.Append(33, "cc") list.Insert(5, "zz") list.Insert(15, "xx") list.Insert(15, "xx") list.Delete(5) list.Delete(33) list.Delete(15) list.Show() }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律