代码如下:
#include <stdio.h>
#include <malloc.h>
#define TOTAL_SPACE 5
typedef struct CircleIntQueue{
int data[TOTAL_SPACE];
int front;
int rear;
}*CircleIntQueuePtr;
CircleIntQueuePtr initQueue() {
CircleIntQueuePtr resultPtr = (CircleIntQueuePtr)malloc(sizeof(struct CircleIntQueue));
resultPtr->front = 0;
resultPtr->rear = 0;
return resultPtr;
}
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) {
printf("Enqueue: %d ", paraValue);
if ((paraPtr->rear + 1) % TOTAL_SPACE == paraPtr->front) {
printf("Queue full.\r\n");
return;
}
paraPtr->data[paraPtr->rear] = paraValue;
paraPtr->rear = (paraPtr->rear + 1) % TOTAL_SPACE;
}
int dequeue(CircleIntQueuePtr paraPtr) {
int resultValue;
if (paraPtr->front == paraPtr->rear) {
printf("No element in the queue.\r\n");
return -1;
}
resultValue = paraPtr->data[paraPtr->front];
paraPtr->front = (paraPtr->front + 1) % TOTAL_SPACE;
return resultValue;
}
void outputCircleIntQueue(CircleIntQueuePtr paraPtr){
int i;
if (paraPtr->front == paraPtr->rear) {
printf("Empty queue.");
return;
}
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]);
}
printf("\r\n");
}
void testCircleIntQueue(){
int i = 10;
CircleIntQueuePtr tempPtr = initQueue();
for (; i < 16; i ++) {
enqueue(tempPtr, i);
}
outputCircleIntQueue(tempPtr);
for (i = 0; i < 6; i ++) {
printf("dequeue gets %d\r\n", dequeue(tempPtr));
}
for (i = 3; i < 6; i ++) {
enqueue(tempPtr, i);
}
for (i = 20; i < 30; i ++) {
enqueue(tempPtr, i);
printf("dequeue gets %d\r\n", dequeue(tempPtr));
outputCircleIntQueue(tempPtr);
}
}
int main(){
testCircleIntQueue();
return 1;
}
运行结果如下:
Enqueue: 10 Enqueue: 11 Enqueue: 12 Enqueue: 13 Enqueue: 14 Queue full.
Enqueue: 15 Queue full.
Elements in the queue: data[0] = 10, data[1] = 11, data[2] = 12, data[3] = 13,
dequeue gets 10
dequeue gets 11
dequeue gets 12
dequeue gets 13
No element in the queue.
dequeue gets -1
No element in the queue.
dequeue gets -1
Enqueue: 3 Enqueue: 4 Enqueue: 5 Enqueue: 20 dequeue gets 3
Elements in the queue: data[0] = 4, data[1] = 5, data[2] = 20,
Enqueue: 21 dequeue gets 4
Elements in the queue: data[1] = 5, data[2] = 20, data[3] = 21,
Enqueue: 22 dequeue gets 5
Elements in the queue: data[2] = 20, data[3] = 21, data[4] = 22,
Enqueue: 23 dequeue gets 20
Elements in the queue: data[3] = 21, data[4] = 22, data[0] = 23,
Enqueue: 24 dequeue gets 21
Elements in the queue: data[4] = 22, data[0] = 23, data[1] = 24,
Enqueue: 25 dequeue gets 22
Elements in the queue: data[0] = 23, data[1] = 24, data[2] = 25,
Enqueue: 26 dequeue gets 23
Elements in the queue: data[1] = 24, data[2] = 25, data[3] = 26,
Enqueue: 27 dequeue gets 24
Elements in the queue: data[2] = 25, data[3] = 26, data[4] = 27,
Enqueue: 28 dequeue gets 25
Elements in the queue: data[3] = 26, data[4] = 27, data[0] = 28,
Enqueue: 29 dequeue gets 26
Elements in the queue: data[4] = 27, data[0] = 28, data[1] = 29,