2019-12-07 14:20:59 +08:00
|
|
|
package util
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
2019-12-07 14:20:59 +08:00
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
type node[T any]struct {
|
|
|
|
data T
|
|
|
|
next *node[T]
|
2019-12-07 14:20:59 +08:00
|
|
|
}
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
type Queue[T any] struct {
|
|
|
|
head *node[T]
|
|
|
|
tail *node[T]
|
2019-12-07 14:20:59 +08:00
|
|
|
count int
|
|
|
|
sync.RWMutex
|
|
|
|
}
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
func NewQueue[T any]() *Queue[T] {
|
|
|
|
q := &Queue[T]{}
|
2019-12-07 14:20:59 +08:00
|
|
|
return q
|
|
|
|
}
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
func (q *Queue[T]) Len() int {
|
2019-12-07 14:20:59 +08:00
|
|
|
q.RLock()
|
|
|
|
defer q.RUnlock()
|
|
|
|
return q.count
|
|
|
|
}
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
func (q *Queue[T]) Enqueue(item T) {
|
2019-12-07 14:20:59 +08:00
|
|
|
q.Lock()
|
|
|
|
defer q.Unlock()
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
n := &node[T]{data: item}
|
2019-12-07 14:20:59 +08:00
|
|
|
|
|
|
|
if q.tail == nil {
|
|
|
|
q.tail = n
|
|
|
|
q.head = n
|
|
|
|
} else {
|
|
|
|
q.tail.next = n
|
|
|
|
q.tail = n
|
|
|
|
}
|
|
|
|
q.count++
|
|
|
|
}
|
|
|
|
|
2024-06-29 05:57:20 +08:00
|
|
|
func (q *Queue[T]) Dequeue() (result T) {
|
2019-12-07 14:20:59 +08:00
|
|
|
q.Lock()
|
|
|
|
defer q.Unlock()
|
|
|
|
|
|
|
|
if q.head == nil {
|
2024-06-29 05:57:20 +08:00
|
|
|
return
|
2019-12-07 14:20:59 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
n := q.head
|
|
|
|
q.head = n.next
|
|
|
|
|
|
|
|
if q.head == nil {
|
|
|
|
q.tail = nil
|
|
|
|
}
|
|
|
|
q.count--
|
|
|
|
|
|
|
|
return n.data
|
2019-12-09 11:44:16 +08:00
|
|
|
}
|
2024-07-11 15:04:24 +08:00
|
|
|
|
|
|
|
func (q *Queue[T]) Peek() (result T) {
|
|
|
|
q.RLock()
|
|
|
|
defer q.RUnlock()
|
|
|
|
|
|
|
|
if q.head == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
return q.head.data
|
|
|
|
}
|