顺序队列基本操作
代码如下:
#include<stdio.h>
#include<stdlib.h>
#define Queue_INITSIZE 20
#define Queue_INCREAMENT 10
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef struct node //定义数据类型
{
ElemType *elem;
int front,rear;
int queuesize;
}SeqQueue;
int menu() //菜单
{
int e;
printf("==========顺序队列==========\n");
printf("=======1.顺序队列初始化=====\n");
printf("=======2.顺序队列元素入队===\n");
printf("=======3.顺序队列元素出队===\n");
printf("=======4.顺序队列求长度=====\n");
printf("=======5.顺序队列判空操作===\n");
printf("=======6.顺序队列判满操作===\n");
printf("=======7.顺序队列清空操作===\n");
printf("please input your diraction:");
scanf("%d",&e);
return e;
}
int initqueue(SeqQueue *q) //顺序队列初始化
{
q->elem=(SeqQueue *)malloc(sizeof(SeqQueue)*Queue_INITSIZE);
q->front=q->rear=0;
q->queuesize=Queue_INITSIZE;
return OK;
}
int enqueue(SeqQueue *q,int e) //入队列
{
if((q->rear+1)%q->queuesize==q->front)
return ERROR;
q->elem[q->rear]=e;
q->rear=(q->rear+1)%q->queuesize;
return OK;
}
int dequeue(SeqQueue *q, int *e) //出队列
{
if(q->rear==q->front)
return ERROR;
else
*e=q->elem[q->front];
q->front=(q->front+1)%q->queuesize;
return OK;
}
int queueempty(SeqQueue *q) //判空操作
{
if(q->rear==q->front)
return OK;
else
return ERROR;
}
int clearqueue(SeqQueue *q) //清空操作
{
q->rear=q->front=0;
return OK;
}
int manqueue(SeqQueue *q) //判满操作
{
if((q->rear+1)%q->queuesize==q->front)
return OK;
else
return ERROR;
}
int queue(SeqQueue *q) //求队列长度
{
int j;
j=q->rear-q->front+q->queuesize;
return j;
}
int main() //主函数
{
SeqQueue *q;
int j,a,*f,e;
while(1)
{
j=menu();
switch(j)
{
case 1:system("cls");
a=initqueue(&q);
if(a==1)
printf("顺序队列初始化成功\n");
break;
case 2:system("cls");
printf("请输入入队列的元素\n");
scanf("%d",&e);
a=enqueue(&q,e);
if(a==1)
printf("顺序队列元素入队成功\n");
else
printf("顺序队列元素入队失败\n");
break;
case 3:system("cls");
a=dequeue(&q,&f);
if(a==1)
printf("顺序队列元素出队成功\n");
else
printf("顺序队列元素出队失败\n");
printf("出队元素的值为:%d\n",f);
break;
case 4:system("cls");
j=queue(&q);
printf("顺序队列的长度为%d\n",j);
break;
case 5:system("cls");
a=queueempty(&q);
if(a==1)
printf("顺序队列为空队列\n");
else
printf("顺序队列元素不为空\n");
break;
case 6:system("cls");
a=manqueue(&q);
if(a==1)
printf("顺序队列已满\n");
else
printf("顺序队列未满\n");
break;
case 7:system("cls");
a=clearqueue(&q);
if(a==1)
printf("顺序队列已清空\n");
break;
}
}
return 0;
}