循环队列的实现
循环队列
#include<iostream.h>
#include <stdlib.h>
#include <malloc.h>
#include<stdio.h>
#define FALSE 0
#define TRUE 1
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int QueueElementType;
typedef struct
{
QueueElementType element[MAXSIZE];
int front;
int rear;
}SeqQueue;
//初始化
int InitQueue(SeqQueue *Q)
{
Q->front=Q->rear=0;
return(TRUE);
}
//入队
int EnterQueue(SeqQueue *Q,QueueElementType x)
{
if((Q->rear+1)%MAXSIZE==Q->front)
return(FALSE);
Q->element[Q->rear]=x;
Q->rear=(Q->rear+1)%MAXSIZE;
return(TRUE);
}
//出队
int DeleteQueue(SeqQueue *Q,QueueElementType *x)
{
if(Q->front==Q->rear)
return(FALSE);
*x=Q->element[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return(TRUE);
}
//求长度
int LengthQueue(SeqQueue *Q)
{
printf("%d",(Q->rear-Q->front+MAXSIZE) % MAXSIZE);
printf("\n");
return(TRUE);
}
//输出链表
void PrintfQueue(SeqQueue *Q)
{
int j;
if(Q->front==Q->rear)
cout<<"队列为空"<<endl;
else
{
j=((Q->rear-Q->front+MAXSIZE) % MAXSIZE)-1;
for(int i=0; i<=j; i++)
printf("%d",Q->element[(Q->front+i)%MAXSIZE]);
printf("\n");
}
}
//判断循环队列是否为空或为满
void JudgeQueue(SeqQueue *Q)
{
if(Q->front==Q->rear)
{
printf("该队列为空");
printf("\n");
}
else if((Q->rear+1)%MAXSIZE==Q->front)
{
printf("该队列为满");
printf("\n");
}
else
{
printf("该队列既不为空也不为满");
printf("\n");
}
}
//销毁队列
void DestroyQueue(SeqQueue *Q)
{
Q->front=Q->rear=0;
}
void main()
{
SeqQueue Q;
InitQueue(&Q);
int flag=1;
printf(" ************^^^^^^^循环队列功能菜单^^^^^^^************");
printf("\n");
printf("请选择操作:");
printf("\n");
printf("1.入队操作");
printf("\n");
printf("2.出队操作");
printf("\n");
printf("3.判断队列空或满");
printf("\n");
printf("4. 求队列长度");
printf("\n");
printf("5.销毁队列");
printf("\n");
printf("6.退出");
printf("\n");
while(flag)
{
int x,e;
cin>>e;
switch(e){
case 1:printf("请输入要入队的整型值:(限一个)");
printf("\n");
cin>>x;
EnterQueue(&Q,x);
printf("队列为:");
PrintfQueue(&Q);
break;
case 2: DeleteQueue(&Q,&x);
printf("队列为:");
PrintfQueue(&Q);
break;
case 3:JudgeQueue(&Q);
break;
case 4:printf("链表长度为:");
LengthQueue(&Q) ;
break;
case 5:DestroyQueue(&Q);
printf("销毁成功!");
break;
case 6:flag=0;
break;
}
}
}
转自:http://mickyxiahcdd.blog.163.com/blog/static/128243967200992003724101/