diff --git a/datastructure/queue/arrayqueue.go b/datastructure/queue/arrayqueue.go index 4532894..ef589f1 100644 --- a/datastructure/queue/arrayqueue.go +++ b/datastructure/queue/arrayqueue.go @@ -136,8 +136,8 @@ func (q *ArrayQueue[T]) Clear() { // Contain checks if the value is in queue or not func (q *ArrayQueue[T]) Contain(value T) bool { - for _, v := range q.data { - if reflect.DeepEqual(v, value) { + for i := q.head; i < q.tail; i++ { + if reflect.DeepEqual(q.data[i], value) { return true } } diff --git a/datastructure/queue/circularqueue.go b/datastructure/queue/circularqueue.go index 9700716..65e8834 100644 --- a/datastructure/queue/circularqueue.go +++ b/datastructure/queue/circularqueue.go @@ -108,8 +108,8 @@ func (q *CircularQueue[T]) Clear() { // Contain checks if the value is in queue or not func (q *CircularQueue[T]) Contain(value T) bool { - for _, v := range q.data { - if reflect.DeepEqual(v, value) { + for i := q.front; i != q.rear; i = (i + 1) % q.capacity { + if reflect.DeepEqual(q.data[i], value) { return true } } diff --git a/datastructure/queue/contain_active_test.go b/datastructure/queue/contain_active_test.go new file mode 100644 index 0000000..72309fe --- /dev/null +++ b/datastructure/queue/contain_active_test.go @@ -0,0 +1,25 @@ +package datastructure + +import "testing" + +func TestQueueContainActiveValues(t *testing.T) { + array := NewArrayQueue[int](5) + array.Enqueue(1) + array.Enqueue(2) + array.Dequeue() + if array.Contain(1) || !array.Contain(2) { + t.Error("array queue includes a dequeued value") + } + circular := NewCircularQueue[int](4) + if circular.Contain(0) { + t.Error("empty circular queue contains a zero value") + } + circular.Enqueue(1) + circular.Enqueue(2) + circular.Dequeue() + circular.Enqueue(3) + circular.Enqueue(4) + if circular.Contain(0) || circular.Contain(1) || !circular.Contain(4) { + t.Error("circular queue did not restrict its search to active values") + } +}