#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAXSIZE 10 //数组队列的最大大小
//先入先出
typedef struct Queue
{
int data[MAXSIZE]; //队列的总大小
int front; //记录队列首元素的下边标量
int rear; //记录队尾元素的小标变量
}queue_q, *Queue_q;
//初始化队列
Queue_q Init_queue(void)
{
Queue_q sq = malloc(sizeof(queue_q)); //申请结构体大小的内存空间,sq指向这片内存空间
if(sq != NULL)
{
sq->front = MAXSIZE - 1;
sq->rear = MAXSIZE -1;
return sq;
}
return 0;
}
//是否为空
bool Is_Empty(Queue_q sq)
{
//为空返回true 否则返回false
return sq->rear == sq->front;
}
//是否已满
bool Is_Full(Queue_q sq)
{
//当(sq->reat + 1) % SIZE和sq->front相等时,返回true(满) 否则返回false(不满)
return (sq->rear + 1) % MAXSIZE == sq->front;
}
//入队
bool Push_queue(Queue_q sq, int n)
{
if(Is_Full(sq))
{
printf("队列已满!\n");
return false;
}
sq->rear = (sq->rear + 1) % MAXSIZE; //先让队尾下标进行偏移
sq->data[sq->rear] = n; //赋值
return true;
}
//出队
bool Out_queue(Queue_q sq, int *t)
{
if(Is_Empty(sq))
{
printf("队列空!\n");
return false;
}
sq->front = (sq->front + 1) % MAXSIZE;
*t = sq->data[sq->front];
return true;
}
//打印队列
bool Show_queue(Queue_q sq)
{
if(Is_Empty(sq))
{
printf("队列空!\n");
return false;
}
for(int i = (sq->front + 1 ) % MAXSIZE; i <= sq->rear; i = (i+1) % MAXSIZE)
{
printf("%d ", sq->data[i]);
}
printf("\n");
}
int main()
{
Queue_q sq = Init_queue();
for(int i = 0; i < 5; i++)
{
Push_queue(sq, i);
}
Show_queue(sq);
int temp;
Out_queue(sq, &temp);
printf("out:%d\n", temp);
Show_queue(sq);
}
结果: