go sdk 1.13.6
// list链表中的元素
type Element struct {
next, prev *Element
list *List
Value interface{}
}
// list链表结构体
// root 为哨兵元素,并不存放实际element,主要作用是方便pushfront和pushback元素到链表
// root的存在方便了list构建为双向ring链表
type List struct {
root Element //注意,这里面root不是指针
len int
}
// list初始化方法
// 可以看出初始化的时候,定义了root自己首尾相连
func (l *List) Init() *List {
l.root.next = &l.root
l.root.prev = &l.root
l.len = 0
return l
}
// list new 方法
func New() *List {
return new(List).Init()
}
// 使用示例
// output
// 1
// 2
// 3
// 4
func Example() {
l := list.New() e4 := l.PushBack(4)
e1 := l.PushFront(1)
l.InsertBefore(3, e4)
l.InsertAfter(2, e1)
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
}