fix(package): [queue] keep circular queues reusable after clear (#394)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-22 10:43:42 +08:00
1 parent 8225b6d7d9
commit fe4c81a677
2 files changed
+21 -3

No files matched your search

+2 -3
View File
@@ -57,7 +57,7 @@ func (q *CircularQueue[T]) IsEmpty() bool {
// IsFull checks if queue is full or not // IsFull checks if queue is full or not
func (q *CircularQueue[T]) IsFull() bool { 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 // Front return front value of queue
@@ -101,10 +101,9 @@ func (q *CircularQueue[T]) Dequeue() (*T, error) {
// Clear the queue data // Clear the queue data
func (q *CircularQueue[T]) Clear() { func (q *CircularQueue[T]) Clear() {
q.data = []T{} q.data = make([]T, q.capacity)
q.front = 0 q.front = 0
q.rear = 0 q.rear = 0
q.capacity = 0
} }
// Contain checks if the value is in queue or not // Contain checks if the value is in queue or not
+19
View File
@@ -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")
}
}