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
|
|
|
}
|