【头文件代码】
#define MAXSIZE 100
typedef int datatype;
typedef struct{
datatype a[MAXSIZE];
int fron;
int rear;
}sequence_queue;//定义数据类型为数组的顺序队
//初始化
void init(sequence_queue *sq)
{
sq->fron=sq->rear=0;
}
//判断队列是否为空
int empty_queue(sequence_queue sq)
{
return (sq.fron==sq.rear?1:0);
}//空则返回1,非空返回0
//打印队列的结点值
void display(sequence_queue sq)
{
int i;
if (empty_queue(sq))
{
printf("\n顺序队列是空的!");
}
else
for (i=sq.fron;i<sq.rear;i++)
printf("[%d]=%d\n",i,sq.a[i]);
}
//取得队首结点的值
datatype get(sequence_queue sq)
{
if (empty_queue(sq))
{
printf("\n顺序队列是空的!");
exit(1);
}
return sq.a[sq.fron];
}
//插入(入队)
void insert_queue(sequence_queue *sq,datatype x)
{
int i;
if (sq->rear==MAXSIZE)
{
printf("\n顺序队列是满的!");
exit(1);
}
sq->a[sq->rear]=x;
sq->rear=sq->rear+1;
}
//删除(出队)
void delete_queue(sequence_queue *sq)
{
if (sq->fron==sq->rear)
{
printf("\n顺序队列是空的!不能做删除操作!");
exit(1);
}
sq->fron++;
}
//插入
void insert_cqueue(sequence_queue *sq,datatype x)
{
if ((sq->rear+1)%MAXSIZE==sq->fron)//牺牲掉一个空间,相当于提前一个元素便告知已满
{
printf("\n顺序循环队列是满的!无法进行插入操作!");
exit(1);
}
sq->a[sq->rear]=x;
sq->rear=(sq->rear+1)%MAXSIZE;//若尾指针在最后一个位置,则下一次就移动到0的位置
}
//删除
void dele_cqueue(sequence_queue *sq)
{
if (sq->fron==sq->rear)
{
printf("\n循环队列是空的!无法进行删除操作!");
exit(1);
}
sq->fron=(sq->fron+1)%MAXSIZE;
}
//具体输入值进队列
void input_queue(sequence_queue *sq)
{
if ((sq->rear+1)%MAXSIZE==sq->fron)//牺牲掉一个空间,相当于提前一个元素便告知已满
{
printf("\n顺序循环队列是满的!无法进行插入操作!");
exit(1);
}
else
{
printf("Please type some message...type '-88' to quit...\n");
while (sq->a[sq->rear-1]!=-88)
{
scanf("%d",&sq->a[sq->rear]);
sq->rear++;
}
sq->rear--;
}
}
【源文件代码】
#include<seqqueue.h>
int main()
{
sequence_queue sq;
init(&sq);
input_queue(&sq);
display(sq);
return 0;
}