#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR -1
#define MAX_SIZE 10
typedef int ElemType;
typedef int Status;
循环队列的结构体
typedef struct Queue
{
ElemType Queue_array[MAX_SIZE];
int front;
int rear;
}SqQueue;
队列的初始化
Status Init_CirQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
return OK;
}
入队列
void EnCirQueue(SqQueue *Q, ElemType e)
{
if((Q->rear + 1)%MAX_SIZE == Q->front)//判断队列是否已满
{
printf("This queue is full.\n");
}
else
{
Q->Queue_array[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAX_SIZE;
printf("success!\n");
}
}
删除队首元素(出队列)
void DeQueue(SqQueue *Q)
{
if(Q->front == Q->rear)//判断栈是否为空
{
printf("This queue is empty!\n");
}
else
{
Q->front = (Q->front + 1) % MAX_SIZE;
printf("Delete success!\n");
}
}
遍历队列
Status QueueTraverse(SqQueue *Q)
{
int j = 0;//元素个数计数器
int p;
p = Q->front;
while(p % MAX_SIZE != Q->rear)
{
p = (p + 1) % MAX_SIZE;
j++;
}
printf("队列长度为:%d\n", j);
return j;
}
打印输出队列
void OutPut_Queue(SqQueue *Q)
{
int p;
int j = 1;
p = Q->front;
if(Q->front == Q->rear)
{
printf("This queue is empty!\n");
}
else
{
while(p % MAX_SIZE != Q->rear)
{
printf("第%d个元素为:%d\n", j, Q->Queue_array[p]);
p = (p + 1) % MAX_SIZE;
j++;
}
}
}
在主方法中调用上述方法
int main()
{
int i = 0;
int res1 = 0;//初始化队列的返回值
int j = 0;
SqQueue Q;
//根据操作编号自己选择操作
printf("1.初始化队列\n2.入队列\n3.输出队列\n4.遍历队列\n5.删除队首元素\n");
while(1)
{
printf("请输入操作编号:");
scanf("%d", &i);
printf("\n");
if(i == 1)
{
printf("----------初始化队列---------\n");
res1 = Init_CirQueue(&Q);
if(res1 == OK)
printf("初始化成功\n");
else
printf("初始化失败\n");
j++;
}
else if(i == 2)
{
if(j == 0)
{
printf("Please initialize a queue first!\n\n");
}
else
{
int a;
printf("----------入队列---------\n");
printf("请输入数据:");
scanf("%d", &a);
EnCirQueue(&Q, a);
}
}
else if(i == 3)
{
if(j == 0)
{
printf("Please initialize a queue first!\n");
}
else
{
printf("----------输出队列---------\n");
OutPut_Queue(&Q);
}
}
else if(i == 4)
{
if(j == 0)
{
printf("Please initialize a queue first!\n");
}
else
{
printf("----------遍历队列---------\n");
QueueTraverse(&Q);
}
}
else if(i == 5)
{
if(j == 0)
{
printf("Please initialize a queue first!\n");
}
else
{
printf("----------删除队首元素---------\n");
DeQueue(&Q);
}
}
else
{
printf("操作编码错误!\n\n请重新输入!\n");
}
}
return 0;
}
用的不同的编程软件,在编译过程汉字也许会出现乱码或编译出错等情况,若出现,把汉字改成英文就OK了