#include <stdio.h>
#include <stdlib.h>
#define N 6
typedef struct
{
int data[N];
int tail;//队尾:放数据端
int head;//队头:取数据端
}LoopQueue;
// 创建空队列
LoopQueue* initQueue()
{
LoopQueue* p = (LoopQueue*)malloc(sizeof(LoopQueue));
if (p == NULL)
{
perror("init malloc err\n");
return NULL;
}
// 初始化
p->head = 0;//队头
p->tail = 0;//队尾:当其加1=N时,此时认为队列已满
return p;
}
// 判空
int isNullQueue(LoopQueue* p)
{
return p->head == p->tail;
}
// 判满
int isFullQueue(LoopQueue* p)
{
return (p->tail +1) % N == 0;
}
// 入列
void inQueue(LoopQueue* p, int data)
{
// 判满
if (isFullQueue(p))//判断队列是否满,
{
printf("队列满!\n");
return;
}
//没满数据存入列
p->data[p->tail] = data;
// 队尾向后移动
p->tail = (p->tail +1) % N;
}
// 出列
void outQueue(LoopQueue* p)
{
// 容错判断
if (isNullQueue(p))
{
printf("空队!\n");
return;
}
// 保存出列数据
int temp = p->data[p->head];
// 队头向后移动
p->head = (p->head + 1) % N;
printf("出列:%d\n", temp);
}
// 清空队列
void noneQueue(LoopQueue* p)
{
while(!isNullQueue(p))
{
outQueue(p);
}
}
// 队列长度:存在tail<head的情况
void queueLength(LoopQueue* p)
{
if (p->head < p->tail)
{
printf("队长:%d\n", p->tail - p->head);
}
else
{
printf("队长:%d\n", p->tail - p->head + N);
}
}
// 遍历:存在tail<head的情况
void printQueue(LoopQueue* p)
{
for (int i = p->head; i < p->tail; i++)//这里不能等于tail,因为p->data[5]不储存数,所以不打印
{
printf("%d-", p->data[i]);
}
printf("NULL\n");
}
int main(int argc, char const *argv[])
{
LoopQueue* p = initQueue();
inQueue(p, 1);
inQueue(p, 2);
inQueue(p, 3);
inQueue(p, 4);
inQueue(p, 5);
queueLength(p);
// inQueue(p, 6);
printQueue(p);
outQueue(p);
queueLength(p);
printQueue(p);
noneQueue(p);
printQueue(p);
return 0;
}
循环队列操作集合
最新推荐文章于 2023-09-21 19:58:44 发布