From fe4c81a677a85f33e88052bc523c856ce06fe511 Mon Sep 17 00:00:00 2001 From: Yusuf Efe <120668197+yuefdev@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:43:42 +0300 Subject: [PATCH] fix(package): [queue] keep circular queues reusable after clear (#394) --- datastructure/queue/circularqueue.go | 5 ++--- datastructure/queue/clear_reuse_test.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 datastructure/queue/clear_reuse_test.go diff --git a/datastructure/queue/circularqueue.go b/datastructure/queue/circularqueue.go index b33ba55..9700716 100644 --- a/datastructure/queue/circularqueue.go +++ b/datastructure/queue/circularqueue.go @@ -57,7 +57,7 @@ func (q *CircularQueue[T]) IsEmpty() bool { // IsFull checks if queue is full or not func (q *CircularQueue[T]) IsFull() bool { - return (q.rear+1)%q.capacity == q.front + return q.capacity == 0 || (q.rear+1)%q.capacity == q.front } // Front return front value of queue @@ -101,10 +101,9 @@ func (q *CircularQueue[T]) Dequeue() (*T, error) { // Clear the queue data func (q *CircularQueue[T]) Clear() { - q.data = []T{} + q.data = make([]T, q.capacity) q.front = 0 q.rear = 0 - q.capacity = 0 } // Contain checks if the value is in queue or not diff --git a/datastructure/queue/clear_reuse_test.go b/datastructure/queue/clear_reuse_test.go new file mode 100644 index 0000000..828dcb8 --- /dev/null +++ b/datastructure/queue/clear_reuse_test.go @@ -0,0 +1,19 @@ +package datastructure + +import "testing" + +func TestCircularQueueReuseAfterClear(t *testing.T) { + queue := NewCircularQueue[int](3) + queue.Enqueue(1) + queue.Clear() + if err := queue.Enqueue(2); err != nil { + t.Fatal(err) + } + if queue.Size() != 1 || queue.Front() != 2 { + t.Error("cleared queue could not be reused") + } + zero := NewCircularQueue[int](0) + if !zero.IsFull() || zero.Enqueue(1) == nil { + t.Error("zero-capacity queue should reject an element") + } +}