Go list的介绍与使用
介绍
Go的list是一个双向链表,链表可以高效的删除插入元素,很多场景是需要用到这个结构的,比如cache
使用
list在包container/list下,可以通过NeW()初始化或者var声明
两种方法如下
mylist := list.New()
var mylist list.List
-
常用的函数以及功能如下表格
| 函数|功能 |
| :------------ | :------------ |
|PushFront(v any) *Element|在最前插入元素 |
|PushBack(v any) *Element|在最后插入元素 |
|InsertBefore(v any, mark *Element) *Element|将元素插到mark前 |
|InsertAfter(v any, mark *Element) *Element|将元素插到mark后 |
|MoveToFront(e *Element)|将指定元素移到最前|
|MoveToBack(e *Element)|将指定元素移到最后|
|MoveBefore(e, mark *Element)|将指定元素移到mark前|
|MoveAfter(e, mark *Element)|将指定元素移到mark后|
|PushBackList(other *List)|将另一个list插入到当前list后 |
|PushFrontList(other *List)|将另一个list插入到当前list前|
|Remove(e *Element) any|删除指定元素|
|Len()|返回list长度| -
demo
package main
import (
"container/list"
"fmt"
)
func main() {
mylist := list.New()
one := mylist.PushFront("first")
two := mylist.PushBack("second")
head := mylist.InsertAfter("third", one)
three := mylist.InsertAfter(4, two)
mylist.Remove(three)
mylist.MoveToFront(head)
for e := mylist.Front(); e != nil; e = e.Next() {
fmt.Printf("%v ", e.Value)//third first second
}
}
list 当堆队列用
package main
import (
"container/list"
"fmt"
)
func main() {
//q := list.List{}
// 堆
q := list.New()
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(4)
for q.Len() > 0 {
cur := q.Back().Value.(int) // 类型转换,方便后续操作
q.Remove(q.Back())
// 下面这样写更简介些,少些一行
//cur := q.Remove(q.Back()).(int)
fmt.Println(cur) // 4 3 2 1
}
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(4)
for q.Len() > 0 {
//cur := q.Back().Value.(int) // 类型转换,方便后续操作
//q.Remove(q.Back())
// 下面这样写更简介些,少些一行
//通过q.Back q.Front q.PushBack q.PushFront , 即刻实现双端队列
cur := q.Remove(q.Front()).(int)
fmt.Println(cur) // 1 2 3 4
}
}

浙公网安备 33010602011771号