1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
lqueue.go 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-10-12 22:45 . 任务调度器
package queue
type node struct {
next *node
val interface{}
}
var _ Queue = (*LQueue)(nil)
type LQueue struct {
head *node
tail *node
length int
capacity int
}
func NewLQueue(capacity int) *LQueue {
if capacity <= 0 {
capacity = minCapacity
}
if capacity > maxCapacity {
capacity = maxCapacity
}
return &LQueue{capacity: capacity}
}
func (lq *LQueue) Add(val interface{}) error {
if lq.length >= lq.capacity {
return ErrIsFull
}
item := &node{
val: val,
}
item.next = lq.head
lq.head = item
lq.length++
return nil
}
func (lq *LQueue) AddTail(val interface{}) error {
if lq.length >= lq.capacity {
return ErrIsFull
}
item := &node{
val: val,
}
if lq.tail == nil {
lq.head = item
} else {
lq.tail.next = item
}
lq.length++
lq.tail = item
return nil
}
func (lq *LQueue) Pop() interface{} {
if lq.head != nil {
val := lq.head.val
lq.head = lq.head.next
if lq.head == nil {
lq.tail = nil
}
lq.length--
return val
}
return nil
}
func (lq *LQueue) Peek() interface{} {
if lq.head != nil {
return lq.head.val
}
return nil
}
func (lq *LQueue) Empty() bool {
return lq.head == nil
}
func (lq *LQueue) Len() int {
return lq.length
}
func (lq *LQueue) Cap() int {
return lq.length
}
// Find return index -1 not found.
func (lq *LQueue) Find(fn IndexFunc) (interface{}, int) {
index := 0
for i := lq.head; i != nil; i = i.next {
if fn(i.val, index) {
return i.val, index
}
index++
}
return nil, -1
}
func (lq *LQueue) ToList() []interface{} {
buf := make([]interface{}, lq.Len())
index := 0
for i := lq.head; i != nil; i = i.next {
buf[index] = i.val
index++
}
return buf
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.3.56

搜索帮助