要使用普通数组实现队列,只需循环处理它 - 因此,一旦数组中的空间用完,就回绕到 0。正如您所指出的,您需要保留前后的记录。举个例子(其中 X 代表队列中的一个项目):
// Rear is where to enqueue into, Front is where to dequeue from
Empty Array:
| - - - |
Front = -1, Rear = 0
Enqueue()
| X - - |
Front = 0, Rear = 1
Enqueue()
| X X - |
Front = 0, Rear = 2
Dequeue()
| - X - |
Front = 1, Rear = 2
Enqueue()
| - X X |
Front = 1, Rear = 0 // Looped around
Dequeue()
| - - X |
Front = 2, Rear = 0
Enqueue()
| X - X |
Front = 2, Rear = 1
你只需要使用模运算来环绕。当然,这在大小上是有限的(一旦元素用完,就必须分配更多内存),但这正是处理数组时得到的。
这是一些代码作为开始(我根本没有检查过):
// Private class variables:
// These should be set in the constructor of your queue class
unsigned int rear = 0; // back of the queue
unsigned int front = -1; // front of the queue
unsigned int numStored = 0;
unsigned int length;
Object* array = new Object[length];
QueueAr::Enqueue(Object& obj)
{
if (front == rear)
{
// Throw an exception: queue is full!
}
else
{
array[rear] = obj; // Insert the object at the back
rear++;
rear = rear % length;
numStored++;
}
}
// For kicks, here's the queue code
QueueAr::Dequeue(Object& obj)
{
if (numStored == 0)
{
// Throw an exception: queue is empty!
}
front++;
front = front % length;
numStored--;
}