CircularQueue.h文件
#ifndef CIRCULARQUEUE_H
#define CIRCULARQUEUE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 5
//定义队列数据结构
typedef struct CIRCULARQUEUE
{
void *data[MAX_SIZE]; //数组实现顺序队列结构
int rear; //队尾rear
int front; //队首front
}CircularQueue;
//初始化队列
CircularQueue *Init_CircularQueue();
//销毁队列
void Free_CircularQueue(CircularQueue *queue);
//队列是否为空
int IsEmpty_CircularQueue(CircularQueue *queue);
//入队列
void Insert_CircularQueue(CircularQueue *queue , void *data);
//出队列
void *Remove_CircularQueue(CircularQueue *queue);
#endif
CircularQueue.c文件
#include "CircularQueue.h"
//初始化队列
CircularQueue *Init_CircularQueue()
{
CircularQueue *queue = (CircularQueue *)malloc(sizeof(CircularQueue));
//初始化队列
int i;
for(i = 0; i < MAX_SIZE; i++)
{
queue->data[i] = NULL;
}
queue->front = 0;
queue->rear = 0;
return queue;
}
//销毁队列
void Free_CircularQueue(CircularQueue *queue)
{
if(queue == NULL)
{
return;
}
free(queue);
queue = NULL;
}
//队列是否为空
int IsEmpty_CircularQueue(CircularQueue *queue)
{
if(queue == NULL)
{
return -1;
}
//队列为空返回0,不为空返回1
if(queue->front == queue->rear)
{
return 0;
}
return 1;
}
//入队列
void Insert_CircularQueue(CircularQueue *queue , void *data)
{
if(queue == NULL || data == NULL)
{
return;
}
//判断队列是否已满
if( (queue->rear + 1) % MAX_SIZE == queue->front )
{
return;
}
//数据元素入队
queue->rear = (queue->rear + 1) % MAX_SIZE;
queue->data[queue->rear] = data;
}
//出队列
void *Remove_CircularQueue(CircularQueue *queue)
{
if(queue == NULL)
{
return NULL;
}
//队列为空
if(queue->rear == queue->front)
{
return NULL;
}
//数据元素出队
queue->front = (queue->front + 1) % MAX_SIZE;
return queue->data[queue->front];
}
main.c文件
#include "CircularQueue.h"
typedef struct STUDENT
{
char name[20];
int age;
}Student;
int main(void)
{
//创建循环队列
CircularQueue *queue = Init_CircularQueue();
//创建数据
Student s1 = {"xiaoming",17};
Student s2 = {"zhangsan" , 20};
Student s3 = {"lisi" , 27};
Student s4 = {"wangwu" , 18};
printf("---------------入队--------------\n\n");
//入队
Insert_CircularQueue(queue , (void *)&s1);
Insert_CircularQueue(queue , (void *)&s2);
Insert_CircularQueue(queue , (void *)&s3);
Insert_CircularQueue(queue , (void *)&s4);
printf("---------------出队--------------\n");
//输出队列
//注意:循环队列的数组空间大小定义为5,但实际上循环队列能存储的数据元素大小只有4
//也就是说,当我们在进行入队时,队列中的数据元素的个数不能超过4,否则将会数组越界
int i;
for(i = 0; i < MAX_SIZE - 1; i++)
{
//出队
Student *temp = (Student *)Remove_CircularQueue(queue);
printf("name = %s , age = %d\n" , temp->name , temp->age);
}
printf("---------------释放队列--------------\n");
//释放队列
Free_CircularQueue(queue);
return 0;
}
测试结果:
虽然在定义循环队列的数组存储空间大小是5,但实际上循环队列的存储空间大小只有4,如果超过4则会导致数组越界。