go源码阅读 - container/list

container/list实际上是一个双向链表。

// Element is an element of a linked list.
type Element struct {
// Next and previous pointers in the doubly-linked list of elements.
// To simplify the implementation, internally a list l is implemented
// as a ring, such that &l.root is both the next element of the last
// list element (l.Back()) and the previous element of the first list
// element (l.Front()).
next, prev *Element
// The list to which this element belongs.
list *List
// The value stored with this element.
Value interface{}
}

Element是一个元素Node,提供 Next() Prev()这类常规操作。
// Next returns the next list element or nil.
func (e *Element) Next() *Element {
if p := e.next; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element {
if p := e.prev; e.list != nil && p != &e.list.root {
return p
}
return nil
}
// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
// 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
}

func New() *List //创建一个双向链表
func (l *List) Back() *Element //返回双向链表上一个元素
func (l *List) Front() *Element //返回双向链表下一个元素
func (l *List) Init() *List //初始化链表
func (l *List) InsertAfter(v interface{}, mark *Element) *Element //在指定节点后插入,成功返回插入节点的指针,失败返回nil, 时间复杂度O(1)
func (l *List) InsertBefore(v interface{}, mark *Element) *Element //在指定节点之前插入, 成功返回插入节点的指针,失败返回nil, 时间复杂度O(1)
func (l *List) Len() int //返回链表长度,时间复杂度O(1)
func (l *List) MoveAfter(e, mark *Element) //移动节点e到mark节点之后,时间复杂度O(1), 处理方式:先删除然后再插入
func (l *List) MoveBefore(e, mark *Element) //移动节点e到mark节点之前,时间复杂度O(1), 处理方式:先删除然后再插入
func (l *List) MoveToBack(e *Element) //移动节点e到链表的尾部
func (l *List) MoveToFront(e *Element) //移动节点e到链表的头部
func (l *List) PushBack(v interface{}) *Element //在链表尾部追加值为v的新节点
func (l *List) PushBackList(other *List) //把链表other所有节点追加到当前链表的尾部
func (l *List) PushFront(v interface{}) *Element //在链表的头部插入新节点
func (l *List) PushFrontList(other *List) //把链表other所有节点追加到当前链表头部
func (l *List) Remove(e *Element) interface{} //删除指定节点


List在内部是一个循环链表,他的root元素永远不会持有任何的元素值,root元素的存在就是为了连接这个链表的首尾两端。也就是说,list的零值是一个只包含根元素,但是不包含任何实际元素值的空链表。

posted @ 2021-04-19 16:29  卷毛狒狒  阅读(93)  评论(0编辑  收藏  举报