基础使用
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/glist"
)
func main() {
// Not concurrent-safe in default.
l := glist.New()
// Push
l.PushBack(1) //从后面插入值
l.PushBack(2) //从后面插入值
e := l.PushFront(0) //从前面插入值
// Insert
l.InsertBefore(e, -1) //从0的前面插入值
l.InsertAfter(e, "a") //从0的后面插入值
fmt.Println(l)
// Pop Pop 出栈后,从list里移除
fmt.Println(l.PopFront()) // 从前面出栈,返回出栈的值
fmt.Println(l.PopBack()) //从后面出栈
fmt.Println(l)
// All
fmt.Println(l.FrontAll()) //正序返回一个复本
fmt.Println(l.BackAll()) //逆序返回一个复本
// Output:
// [-1,0,"a",1,2]
// -1
// 2
// [0,"a",1]
// [0 "a" 1]
// [1 "a" 0]
}
链表遍历
该示例中我们将通过读锁和写锁遍历一个并发安全的链表,分别通过 RLockFunc
和 LockFunc
实现。执行后,输出结果为:
package main
import (
"container/list"
"fmt"
"github.com/gogf/gf/v2/container/garray"
"github.com/gogf/gf/v2/container/glist"
)
func main() {
// concurrent-safe list.
l := glist.NewFrom(garray.NewArrayRange(1, 9, 1).Slice(), true)
fmt.Println(l)
// iterate reading from head.
l.RLockFunc(func(list *list.List) {
length := list.Len()
if length > 0 {
for i, e := 0, list.Front(); i < length; i, e = i+1, e.Next() {
fmt.Print(e.Value)
}
}
})
fmt.Println()
// iterate reading from tail.
l.RLockFunc(func(list *list.List) {
length := list.Len()
if length > 0 {
for i, e := 0, list.Back(); i < length; i, e = i+1, e.Prev() {
fmt.Print(e.Value)
}
}
})
fmt.Println()
// iterate reading from head using IteratorAsc.
l.IteratorAsc(func(e *glist.Element) bool {
fmt.Print(e.Value)
return true
})
fmt.Println()
// iterate reading from tail using IteratorDesc.
l.IteratorDesc(func(e *glist.Element) bool {
fmt.Print(e.Value)
return true
})
fmt.Println()
// iterate writing from head.
l.LockFunc(func(list *list.List) {
length := list.Len()
if length > 0 {
for i, e := 0, list.Front(); i < length; i, e = i+1, e.Next() {
if e.Value == 6 {
e.Value = "M"
break
}
}
}
})
fmt.Println(l)
// Output:
// [1,2,3,4,5,6,7,8,9]
// 123456789
// 987654321
// 123456789
// 987654321
// [1,2,3,4,5,M,7,8,9]
Push*
元素项入栈
package main
import (
"fmt"
"github.com/gogf/gf/v2/container/glist"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
l := glist.NewFrom(g.Slice{1, 2, 3, 4, 5})
l.PushBack(6)
fmt.Println(l)
l.PushFront(0)
fmt.Println(l)
// 正数从右边入栈
l.PushBacks(g.Slice{7, 8})
fmt.Println(l)
// 负数从左边入栈
l.PushFronts(g.Slice{-1, -2})
fmt.Println(l)
l.PushFrontList(glist.NewFrom(g.Slice{"a", "b", "c"}))
l.PushBackList(glist.NewFrom(g.Slice{"d", "e", "f"}))
fmt.Println(l)
// Output:
// [1,2,3,4,5,6]
// [0,1,2,3,4,5,6]
// [0,1,2,3,4,5,6,7,8]
// [-2,-1,0,1,2,3,4,5,6,7,8]
// ["a","b","c",-2,-1,0,1,2,3,4,5,6,7,8,"d","e","f"]
}