#include <stdio.h>
#include <malloc.h>
#define TOTAL_SPACE 5
/**
* Circle int queue.
*/
typedef struct CircleIntQueue{
int data[TOTAL_SPACE];
int front;
int rear;
}*CircleIntQueuePtr;
/**
* Initialize the queue.
*/
CircleIntQueuePtr initQueue() {
CircleIntQueuePtr resultPtr = (CircleIntQueuePtr)malloc(sizeof(struct CircleIntQueue));
resultPtr->front = 0;
resultPtr->rear = 0;
return resultPtr;
}// Of the first constructor
/**
* Enqueue.
*
* @param paraValue The value of the new node.
*/
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) {
printf("Enqueue: %d ", paraValue);
if ((paraPtr->rear + 1) % TOTAL_SPACE == paraPtr->front) {
printf("Queue full.\r\n");
return;
} // Of if
paraPtr->data[paraPtr->rear] = paraValue;
paraPtr->rear = (paraPtr->rear + 1) % TOTAL_SPACE;
}// Of enqueue
/**
* Dequeue.
*
* @return The value at the front.
*/
int dequeue(CircleIntQueuePtr paraPtr) {
int resultValue;
if (paraPtr->front == paraPtr->rear) {
printf("No element in the queue.\r\n");
return -1;
} // Of if
resultValue = paraPtr->data[paraPtr->front];
paraPtr->front = (paraPtr->front + 1) % TOTAL_SPACE;
return resultValue;
}// Of dequeue
/**
* Output the queue.
*/
void outputCircleIntQueue(CircleIntQueuePtr paraPtr){
int i;
if (paraPtr->front == paraPtr->rear) {
printf("Empty queue.");
return;
} // Of if
printf("Elements in the queue: ");
for (i = paraPtr->front; i != paraPtr->rear; i = (i + 1) % TOTAL_SPACE) {
printf("data[%d] = %d, ", i, paraPtr->data[i]);
} // Of for i
printf("\r\n");
}//Of outputCircleIntQueue
/**
* Unit test.
*/
void testCircleIntQueue(){
int i = 10;
CircleIntQueuePtr tempPtr = initQueue();
for (; i < 16; i ++) {
enqueue(tempPtr, i);
}//Of for i
outputCircleIntQueue(tempPtr);
for (i = 0; i < 6; i ++) {
printf("dequeue gets %d\r\n", dequeue(tempPtr));
}//Of for i
for (i = 3; i < 6; i ++) {
enqueue(tempPtr, i);
}//Of for i
for (i = 20; i < 30; i ++) {
enqueue(tempPtr, i);
printf("dequeue gets %d\r\n", dequeue(tempPtr));
outputCircleIntQueue(tempPtr);
}//Of for i
}//Of testCircleIntQueue
/**
* The entrance.
*/
int main(){
testCircleIntQueue();
return 1;
}//Of main