#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
循环队列作业
于 2024-05-10 12:23:35 首次发布