//循环队列(队列的顺序存储)
//为了实现循环并且能够判断队列为空为满,则最多能存储N-1个数据
#include <stdio.h>
#include <stdlib.h>
#define N 32
//定义数据类型
typedef int datatype_t;
//定义结构体
typedef struct{
datatype_t data[N];
int front; //保存出队数据的数组下标
int rear; //保存入队数据的数组下标
}sequeue_t;
//创建一个空的队列
sequeue_t *sequeue_create()
{
sequeue_t *sq = (sequeue_t *)malloc(sizeof(sequeue_t));
sq->front = sq->rear = 0;
return sq;
}
//判断为空
int sequeue_empty(sequeue_t *sq)
{
return sq->front == sq->rear ? 1 : 0;
}
//判断为满
int sequeue_full(sequeue_t *sq)
{
return (sq->rear + 1) % N == sq->front ? 1 : 0;
}
//入队
int sequeue_input(sequeue_t *sq, datatype_t value)
{
if(sequeue_full(sq) == 1)
{
printf("sequeue is full\n");
return -1;
}
sq->data[sq->rear] = value;
sq->rear = (sq->rear + 1) % N;
return 0;
}
//出队
datatype_t sequeue_output(sequeue_t *sq)
{
if(sequeue_empty(sq) == 1)
{
printf("sequeue is empty\n");
return (datatype_t)-1;
}
datatype_t value;
value = sq->data[sq->front];
sq->front = (sq->front + 1) % N;
return value;
}
int main(int argc, const char *argv[])
{
sequeue_t *sq = sequeue_create();
sequeue_input(sq, 10);
sequeue_input(sq, 20);
sequeue_input(sq, 30);
sequeue_input(sq, 40);
sequeue_input(sq, 50);
sequeue_input(sq, 60);
while(!sequeue_empty(sq))
{
printf("out data = %d\n", sequeue_output(sq));
}
return 0;
}