package main
import (
"fmt"
)
type List struct {
root Element
len int
}
type Element struct {
next, prev *Element //自己包含自己的类型
list *List
Value interface{}
}
func (l *List) Front() *Element {
if l.len == 0 {
return nil
}
return l.root.next
}
func (l *List) insert(e, at *Element) *Element {
//第一次插入时三个next,prev,list的值是一样的
n := at.next
at.next = e
e.prev = at
e.next = n
n.prev = e
e.list = l
l.len++
fmt.Println("e:", e)
return e
}
func (l *List) Back() *Element {
if l.len == 0 {
return nil
}
return l.root.prev
}
func (e *Element) Next() *Element {
if p := e.next; e.list != nil && p != &e.list.root {
return p
}
return nil
}
func main() {
l := &List{}
l.root.next = &l.root
l.root.prev = &l.root
l.len = 0
fmt.Println("list:", l, l.root.list) //list: &{{0xc0000121b0 0xc0000121b0 <nil> <nil>} 0} <nil>
l.insert(&Element{Value: "fancy"}, l.root.prev)
l.insert(&Element{Value: "lee"}, l.root.prev)
l.insert(&Element{Value: "hello"}, l.root.prev)
fmt.Println("list:", l, *l) //list: &{{0xc000012210 0xc0000122d0 <nil> <nil>} 3} {{0xc000012210 0xc0000122d0 <nil> <nil>} 3}
fmt.Println(l.Front(), l.Front().prev, l.Front().next) //&{0xc000012270 0xc0000121b0 0xc0000121b0 fancy} &{0xc000012210 0xc0000122d0 <nil> <nil>} &{0xc0000122d0 0xc000012210 0xc0000121b0 lee}
fmt.Println(l.Back(), l.Back().prev, l.Back().next) //&{0xc0000121b0 0xc000012270 0xc0000121b0 hello} &{0xc0000122d0 0xc000012210 0xc0000121b0 lee} &{0xc000012210 0xc0000122d0 <nil> <nil>}
}
go 的list
最新推荐文章于 2024-01-21 23:11:17 发布