For the data structure of each queue, we keep an array theArray and its location front and back, which represent the two ends of the queue. We also need to record the number of elements actually present in the queue
CurrentSize.
To enqueue element x, you can increase currentSize and back by 1 and set theArray [back] = x.
To dequeue an element, you can set the return value to theArray [front], reduce currentSize by 1, and then increase front by 1.
As long as the front or back ends to the end of the array, it will return to the beginning. This is called loop array implementation.
[Cpp] www.2cto.com
# Include <stdio. h>
# Define N 10
Int front = 0, back =-1, currentSize = 0;
Void enqueue (int * a, int m)
{
++ Back;
If (front = N)
Front = 0;
If (back = N)
Back = 0;
CurrentSize ++;
A [back] = m;
}
Int dequeue (int *)
{
Return a [front ++];
CurrentSize --;
}
Int main (int argc, char * argv [])
{
Int a [N] = {0 };
Int I;
For (I = 0; I <N; I ++)
Enqueue (a, I );
Enqueue (a, 1 );
// Dequeue ();
For (I = 0; I <N; I ++)
Printf ("% 4d", a [I]);
Return 0;
}