container/list实现双向链表,支持高效插入删除;2. container/heap需自定义类型实现堆接口,适用于优先队列;3. container/ring为循环链表,适合环形数据处理。

list 包实现了双向链表,可以高效地在头部、尾部或中间插入/删除元素。
基本用法:
list.New()
var l list.List
PushFront()
PushBack()
Remove(element)
Front()
Next()
示例:
package main
import (
"container/list"
"fmt"
)
func main() {
l := list.New()
l.PushBack(1)
l.PushBack(2)
l.PushFront(0)
for e := l.Front(); e != nil; e = e.Next() {
fmt.Print(e.Value, " ") // 输出: 0 1 2
}
}
heap 包提供堆操作接口,但需要你实现
heap.Interface
sort.Interface
Push
Pop
立即学习“go语言免费学习笔记(深入)”;
实现步骤:
[]int
heap.Init
heap.Push
heap.Pop
示例:最小堆
package main
import (
"container/heap"
"fmt"
)
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } // 最小堆
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func main() {
h := &IntHeap{3, 1, 4}
heap.Init(h)
heap.Push(h, 2)
for h.Len() > 0 {
fmt.Print(heap.Pop(h), " ") // 输出: 1 2 3 4
}
}
ring 实现了一个单向循环链表,每个节点指向下一个,最后一个指向第一个。
常用方法:
ring.New(n)
r.Value
r.Next()
r.Link()
r.Unlink()
示例:遍历环
package main
import (
"container/ring"
"fmt"
)
func main() {
r := ring.New(3)
for i := 1; i <= 3; i++ {
r.Value = i
r = r.Next()
}
// 遍历
r.Do(func(p interface{}) {
fmt.Print(p, " ") // 输出: 1 2 3
})
}
也可以用
Link
Unlink
以上就是怎样用Golang的container库实现数据结构 heap/list/ring用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号