关于go:go-源码阅读-containerlist

31次阅读

共计 673 个字符,预计需要花费 2 分钟才能阅读完成。

一、介绍

go 语言提供了原生的双向链表,在源码 src/container/list/list.go
双向链表中,每一个元素有 prev,和 next 两个方向。

源码中元素 Element 对应的 构造体为:

// Element is an element of a linked list.
type Element struct {
    // 像一个,高低一个元素
    next, prev *Element

    // The list to which this element belongs.
    list *List

    // The value stored with this element.
    Value interface{}}

源码中 List 的构造体为

type List struct {
    root Element // sentinel list element, only &root, root.prev, and root.next are used
    len  int     // current list length excluding (this) sentinel element
}

通过 New() 函数,新建一个 list。

// New returns an initialized list.
func New() *List { return new(List).Init()}
// Init initializes or clears list l.
func (l *List) Init() *List {
    l.root.next = &l.root
    l.root.prev = &l.root
    l.len = 0
    return l
}

源码中实现一个新 list 分为两步

1、new 一个新 list 构造体
2、初始化 root 的元素的 prev 以及 next 
正文完
 0