一、介绍

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