diff --git a/collections/list.go b/collections/list.go index d8c1d7e..9032cb3 100644 --- a/collections/list.go +++ b/collections/list.go @@ -7,7 +7,10 @@ type List[T any] interface { ToSlice() []T } - -type Queue interface{ - -} \ No newline at end of file +type Queue[T any] interface { + Put(T) + Poll() T + Peek() T + Size() int + IsEmpty() bool +} diff --git a/collections/queue.go b/collections/queue.go index 5e1d424..36644ed 100644 --- a/collections/queue.go +++ b/collections/queue.go @@ -2,6 +2,8 @@ package collections import "sync" +var _ Queue[string] = &ArrayQueue[string]{} + // 数组队列,先进先出 type ArrayQueue[T any] struct { array []T // 底层切片 @@ -14,7 +16,7 @@ func NewArrayQueue[T any]() *ArrayQueue[T] { } // 入队 -func (q *ArrayQueue[T]) Add(v T) { +func (q *ArrayQueue[T]) Put(v T) { q.lock.Lock() defer q.lock.Unlock() @@ -26,7 +28,7 @@ func (q *ArrayQueue[T]) Add(v T) { } // 出队 -func (q *ArrayQueue[T]) Remove() any { +func (q *ArrayQueue[T]) Poll() T { q.lock.Lock() defer q.lock.Unlock() @@ -60,6 +62,10 @@ func (q *ArrayQueue[T]) Remove() any { return v } +func (q *ArrayQueue[T]) Peek() T { + return q.array[0] +} + // 栈大小 func (q *ArrayQueue[T]) Size() int { return q.size diff --git a/collections/rw_queue.go b/collections/rw_queue.go new file mode 100644 index 0000000..1f5afb9 --- /dev/null +++ b/collections/rw_queue.go @@ -0,0 +1,42 @@ +package collections + +import "sync" + +type rw_queue[T any] struct { + q Queue[T] + mu sync.Mutex +} + +func (q *rw_queue[T]) Push(v T) { + q.mu.Lock() + q.q.Put(v) + q.mu.Unlock() +} + +func (q *rw_queue[T]) Pop() T { + q.mu.Lock() + defer q.mu.Unlock() + + return q.q.Poll() +} + +func (q *rw_queue[T]) Peek() T { + q.mu.Lock() + defer q.mu.Unlock() + + return q.q.Peek() +} + +func (q *rw_queue[T]) Size() int { + q.mu.Lock() + defer q.mu.Unlock() + + return q.q.Size() +} + +func (q *rw_queue[T]) IsEmpty() bool { + q.mu.Lock() + defer q.mu.Unlock() + + return q.q.IsEmpty() +}