go 的list

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>}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值