patterncsharpModerate
Circular Bounded Queue using C#
Viewed 0 times
boundedcircularqueueusing
Problem
As an exercise, I have implemented a circular bounded queue using arrays as the base data structure. I'd appreciate it if someone can review it for me.
class BoundedQueue {
T[] que;
int head; // remove from head
int tail; // insert at tail
public BoundedQueue(int quesize)
{
head = tail = -1;
que = new T[quesize];
}
public void enqueue(T elem) // if next index to tail == head => Q is FULL
{
int newIndex = nextIndex(tail);
if ( newIndex == head)
throw new BoundedQueueException(Full);
tail = newIndex;
que[newIndex] = elem;
if (head == -1)
head = 0;
}
public T dequeue() // After removing from head, if that was the only element in Q
// Mark Q to be empty by setting head and tail to -1
{
if (head == -1)
throw new BoundedQueueException(Empty);
T elem = que[head];
que[head] = default(T);
if (head == tail)
{
head = tail = -1;
}
else
{
head = nextIndex(head);
}
return elem;
}
private int nextIndex(int index)
{
return (index + 1) % que.Length;
}
}Solution
- Exception handling should be added
to the constructor, handling a negative
quesize. Or take a look at CodeContracts.
- Instead of initializing
headand
tail to -1, you could usenullable ints, and adjust your
logic so it doesn't rely on the
magic number
-1.- Implement some missing features.
(might have been left out
intentionally): implement
ICollection and IEnumerable, isFull().- A minor point would be naming conventions. In C# method names normally start with a capital letter.
- Be aware that this is not a thread safe class.
- Add some comments, this code isn't that self-documenting. Or, where possible, make it self-documenting, e.g.
if ( head == tail )could beif ( Count == 0 ).
Context
StackExchange Code Review Q#1216, answer score: 15
Revisions (0)
No revisions yet.