#include<stdio.h>
#include<stdlib.h>
#define OK 0
#define ERROR -1
#define MaxSize 20
typedef int status;
typedef int ElemType;
typedef struct
{
ElemType* data;
int front;
int rear;
}Queue;
//初始化队列
status InitQueue(Queue* q)//status搭配前面的define OK 和ERROR食用,只是一个状态函数,用void函数也行
{
q->data = (ElemType*)malloc(MaxSize*sizeof(ElemType));
if(q->data == NULL)
{
printf("初始化失败\n");
return ERROR;
}
q->front = q->rear = 0;
printf("初始化成功\n");
return OK;
}
//入队
status QueuePush(Queue* q,ElemType elem)
{
if((q->rear + 1)%MaxSize == q->front)
{
printf("队满\n");
return ERROR;
}
q->data[q->rear] = elem;
q->rear = (q->rear + 1)%MaxSize;//尾指针加1
printf("入队成功\n");
return OK;
}
//出队
status QueuePop(Queue* q)
{
if(q->rear == q->front)
{
printf("队列为空\n");
return ERROR;
}
q->front++;
printf("出队成功\n");
return OK;
}
//队列判空
status QueueEmpty(Queue* q)
{
if(q->rear == q->front)
{
printf("队列为空\n");
return OK;
}
printf("队列不为空\n");
}
//取队头元素
status QueueFindHead(Queue* q)
{
ElemType x;
if(q->rear == q->front)
{
printf("队列为空\n");
return ERROR;
}
x = q->data[q->front];
printf("队头元素为%d\n",x);
return OK;
}
//取队尾元素
status QueueFindTail(Queue* q)
{
ElemType x;
if(q->rear == q->front)
{
printf("队列为空\n");
return ERROR;
}
x = q->data[q->rear-1];
printf("队尾元素为%d\n",x);
return OK;
}
//打印
void QueuePrint(Queue q)
{
if(q.rear == q.front)
{
printf("队列为空\n");
return;
}
while(q.front != q.rear)
{
printf("%d->",q.data[q.front]);
q.front++;
}
printf("下一循环\n");
}
int main()
{
ElemType elem;
int count;
Queue q;
InitQueue(&q);
printf("请输入想要进行的操作:\n");
printf("1、入队 2、出队 3、判空 4、取头 5、取尾 6、打印 0、结束\n");
while(1)
{
scanf("%d",&count);
switch(count)
{
case 1:
printf("请输入要入队的值:\n");
scanf("%d",&elem);
QueuePush(&q,elem);
break;
case 2:
QueuePop(&q);
break;
case 3:
QueueEmpty(&q);
break;
case 4:
QueueFindHead(&q);
break;
case 5:
QueueFindTail(&q);
break;
case 6:
QueuePrint(q);
break;
case 0:
exit(-1);
default:
printf("ERROR\n");
break;
}
}
return 0;
}
循环队列的基本操作
最新推荐文章于 2024-09-03 20:29:47 发布