本文是 Go 标准库中 container/list 包文档的翻译, 原文地址为: https://golang.org/pkg/container/list/
list 包实现了一个双链表(doubly linked list)。
用户可以通过以下方法来遍历链表, 其中 l 为 *List :
for e := l.Front(); e != nil; e = e.Next() {
// do something with e.Value
}
示例:
package main
import (
"container/list"
"fmt"
)
func main() {
// 创建一个新的链表,并向链表里面添加几个数字
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)
}
}
示例执行结果:
1
2
3
4
Element 用于代表双链表的元素:
type Element struct {
// 储存在这个元素里面的值
Value interface{}
// 其他已过滤或者未导出的字段……
}
List 用于表示双链表。
空列表可以用作 List 的零值。
type List struct {
// contains filtered or unexported fields
}
func (l *List) InsertAfter(v interface{}, mark *Element) *Element
将一个包含了值 v 的新元素 e 添加到元素 mark 的后面, 并返回 e 作为结果。
如果 mark 不是链表的元素, 那么不对链表做任何动作。
func (l *List) InsertBefore(v interface{}, mark *Element) *Element
将一个包含了值 v 的新元素 e 添加到元素 mark 的前面, 并返回 e 作为结果。
如果 mark 不是链表的元素, 那么不对链表做任何动作。
func (l *List) MoveAfter(e, mark *Element)
将元素 e 移动至元素 mark 之后。
如果 e 或者 mark 不是链表的元素, 又或者 e == mark , 那么不对链表做任何动作。
func (l *List) MoveBefore(e, mark *Element)
将元素 e 移动至元素 mark 之前。
如果 e 或者 mark 不是链表的元素, 又或者 e == mark , 那么不对链表做任何动作。
func (l *List) MoveToBack(e *Element)
将元素 e 移动到链表的末尾。
如果 e 不是链表的元素, 那么不对链表做任何动作。
func (l *List) MoveToFront(e *Element)
将元素 e 移动到链表的开头。
如果 e 不是链表的元素, 那么不对链表做任何动作。
func (l *List) PushBackList(other *List)
将链表 other 的副本插入到链表 l 的末尾。 other 和 l 可以是同一个链表。
func (l *List) PushFront(v interface{}) *Element
将包含了值 v 的元素 e 插入到链表的开头并返回 e 。
func (l *List) PushFrontList(other *List)
将链表 other 的副本插入到链表 l 的开头。 other 和 l 可以是同一个链表。
func (l *List) Remove(e *Element) interface{}
如果 e 是链表 l 中的元素, 那么移除元素 e 。
这个方法会返回元素 e 的值 e.Value 作为返回值。
Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License .
本博客中的所有文章均为作者原创,受著作权法律保护,任何人不得在未经授权的情况下转载本博客的文章或将其用于商业活动,违者必究。