代码拉取完成,页面将自动刷新
package queue
type node struct {
next *node
val any
}
var _ Queue = (*Linked)(nil)
// Linked 链表式队列
type Linked struct {
head *node
tail *node
length int
capacity int
}
func NewLinked(capacity int) *Linked {
if capacity <= 0 {
capacity = minCapacity
}
if capacity > maxCapacity {
capacity = maxCapacity
}
return &Linked{capacity: capacity}
}
func (lq *Linked) Add(val any) 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 *Linked) AddTail(val any) 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 *Linked) Push(val any) error {
return lq.Add(val)
}
func (lq *Linked) Pop() any {
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 *Linked) Peek() any {
if lq.head != nil {
return lq.head.val
}
return nil
}
func (lq *Linked) Empty() bool {
return lq.head == nil
}
func (lq *Linked) Len() int {
return lq.length
}
func (lq *Linked) Cap() int {
return lq.length
}
// Find return index -1 not found.
func (lq *Linked) Find(fn IndexFunc) (any, 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 *Linked) ToList() []any {
buf := make([]any, lq.Len())
index := 0
for i := lq.head; i != nil; i = i.next {
buf[index] = i.val
index++
}
return buf
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。