version: 1.10
package list
import "container/list"
概述
list 包实现一个双向链表。
迭代一个链表(这里 l 是一个 List 指针):
for e := l.Front(); e != nil; e = e.Next() {
// do something with e.Value
}
// 创建一个新的链表,然后放入若干数字。
l := list.New()
e4 := l.PushBack(4)
e1 := l.PushFront(1)
l.InsertBefore(3, e4)
l.InsertAfter(2, e1)
// 迭代链表并打印内容。
for e := l.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
// Output:
// 1
// 2
// 3
// 4
索引
- type Element
- type List
- 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
- func (l List) InsertBefore(v interface{}, mark Element) *Element
- func (l *List) Len() int
- func (l List) MoveAfter(e, mark Element)
- func (l List) MoveBefore(e, mark Element)
- func (l List) MoveToBack(e Element)
- func (l List) MoveToFront(e Element)
- func (l List) PushBack(v interface{}) Element
- func (l List) PushBackList(other List)
- func (l List) PushFront(v interface{}) Element
- func (l List) PushFrontList(other List)
- func (l List) Remove(e Element) interface{}
例子
文件
type Element ¶
- type Element struct {
- // 该元素中存储的值。
- Value interface{}
- // 包含被过滤的或未导出的字段
- }
Element 是链表里的一个元素。
func (*Element) Next ¶
Next 方法返回链表里的下一个元素或 nil 。
func (*Element) Prev ¶
Prev 方法返回链表里的前一个元素或 nil 。
type List ¶
- type List struct {
- // contains filtered or unexported fields
- }
List 类型表示一个双向链表。List 的零值表示空链表。
func New ¶
- func New() *List
New 函数初始化一个新链表。
func (*List) Back ¶
Back 方法返回链表的最后一个元素,如果链表是空的则返回 nil 。
func (*List) Front ¶
Front 方法返回链表的第一个元素,如果链表是空的则返回 nil 。
func (*List) Init ¶
Init 方法初始化或清空链表 l 。
func (*List) InsertAfter ¶
InsertAfter 方法在参数 mark 后面插入一个值为 v 的新元素 e 并返回 e 。如果参数 mark 不是 l 的元素,链表不会被修改。参数 mark 一定不能为 nil 。
func (*List) InsertBefore ¶
InsertBefore 方法在参数 mark 前面插入一个值为 v 的新元素 e 并返回 e 。如果参数 mark 不是 l 的元素,链表不会被修改。参数 mark 一定不能为 nil 。
func (*List) Len ¶
Len 方法返回链表 l 中元素的个数。算法的时间复杂度是 O(1)。
func (*List) MoveAfter ¶
MoveAfter 方法移动元素 e 到参数 mark 后面的新位置。如果 e 或 mark 不是链表 l 的元素,或 e 等于 mark,链表不会被修改。e 和 mark 一定不能为 nil 。
func (*List) MoveBefore ¶
MoveBefore 方法移动元素 e 到参数 mark 前面的新位置。如果 e 或 mark 不是链表 l 的元素,或 e 等于 mark,链表不会被修改。e 和 mark 一定不能为 nil 。
func (*List) MoveToBack ¶
MoveToBack 方法移动元素 e 到链表的末尾。如果 e 不是链表 l 的元素,链表不会被修改。e 一定不能为 nil 。
func (*List) MoveToFront ¶
MoveToFront 方法移动元素 e 到链表的开头。如果 e 不是链表 l 的元素,链表不会被修改。e 一定不能为 nil 。
func (*List) PushBack ¶
PushBack 方法插入值为 v 的新元素 e 到链表 l 的末尾,并返回 e 。
func (*List) PushBackList ¶
PushBackList 方法插入链表 other 的一份拷贝到链表 l 的末尾。链表 l 和 other 可能一样,但它们一定不能为 nil 。
func (*List) PushFront ¶
PushFront 方法插入值为 v 的新元素 e 到链表 l 的开头,并返回 e 。
func (*List) PushFrontList ¶
PushFrontList 方法插入链表 other 的一份拷贝到链表 l 的开头。链表 l 和 other 可能一样,但它们一定不能为 nil 。
func (*List) Remove ¶
Remove 方法从链表 l 中移除元素 e 。这个函数返回元素 e 的值,即 e.Value 。元素 e 一定不能为 nil 。