环形队列可以使用数组实现也可以使用循环链表实现
那么怎样判断循环队列的空与满呢?
当q->front==q->rear表示循环队列为空,当(q->rear+1)%maxsize==q->front时,表示循环队列已满。
循环队列的基本操作:
初始化循环队列·
入队列
出队列
检查循环队列是否为空
检查循环队列是否为满
获取循环队列队头元素
获取循环队列队尾元素
释放循环队列
#include <stdio.h>
#include "stdbool.h"
#include "malloc.h"
typedef struct {
int *base;
int front;
int rear;
int capacity;
}CycleQueue;
void CycleQueueInit(CycleQueue* obj,int c)
{
obj->capacity=c;
obj->base=(int*)malloc(sizeof(int)*obj->capacity+1);
obj->front=obj->rear=0;
}
bool IsEmpty(CycleQueue* obj)
{
return obj->rear==obj->front;
}
bool IsFull(CycleQueue* obj)
{
return (obj->rear+1)%(obj->capacity+1)==obj->front;
}
bool CycleQueuePush(CycleQueue* obj, int value) {
if(IsFull(obj))
{
printf("队满");
return 0;
}
obj->base[obj->rear]=value;
obj->rear=(obj->rear+1)%(obj->capacity+1);
}
bool CycleQueuePop(CycleQueue* obj)
{
if(IsEmpty(obj))
{
printf("队空");
return 0;
}
obj->front=(obj->front+1)%(obj->capacity+1);
}
void CycleQueueShow(CycleQueue *obj)
{
for(int i=obj->front;i!=obj->rear;i=(i+1)%(obj->capacity+1))
printf("%d ",obj->base[i]);
}
int CycleQueueFront(CycleQueue* obj) {
if(IsEmpty(obj))
{
printf("队空");
return 0;
}
return obj->base[obj->front];
}
int CycleQueueRear(CycleQueue* obj) {
if(IsEmpty(obj))
{
printf("队空");
return 0;
}
return obj->base[(obj->rear-1+obj->capacity+1)%(obj->capacity+1)];
}
void CycleQueueFree(CycleQueue* obj) {
free(obj->base);
free(obj);
}
int main()
{
CycleQueue q;
CycleQueueInit(&q, 8);
CycleQueuePush(&q, 1);
CycleQueuePush(&q, 3);
CycleQueuePush(&q, 5);
CycleQueuePush(&q, 7);
CycleQueuePush(&q, 9);
CycleQueuePush(&q, 11);
CycleQueuePush(&q, 13);
CycleQueuePush(&q, 15);
CycleQueueShow(&q);
printf("\n");
CycleQueuePop(&q);
CycleQueueShow(&q);
printf("\n");
printf("队头元素为:%d\n",CycleQueueFront(&q));
printf("队尾元素为:%d\n",CycleQueueRear(&q));
}