/*
循环队列——队列的顺序表示和实现
2018.04.20
*/
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
#define OK 1
#define ERROR 0;
#define OVERFLOW -1
typedef int Status;
#define MAXSIZE 100 //队列可达到的最大长度
typedef struct{
char *base; //存储空间的基地址
int front; //头指针
int rear; //尾指针
}SqQueue;
/*
队列为空:font=rear=0;
队列为满:(rear+1)%MAXSIZE=font
*/
//循环队列的初始化
//算法步骤:
//1.为队列分配一个最大容量为MAXSIZE的数组空间,base指向数组空间的首地址;
//2.头指针和尾指针置为零,表示队列为空;
Status InitQueue(SqQueue &Q){
//构造一个空队列
Q.base=new char[MAXSIZE]; //为队列分配一个最大容量为MAXSIZE的数组空间
if(Q.base==NULL)
exit(OVERFLOW); //存储创建失败
Q.front=Q.rear=0; //头指针和尾指针置为零,队列为空
return OK;
}
//求队列的长度
//算法步骤:
//头指针与尾指针的差
int QueueLength(SqQueue Q){
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
//循环队列的入队
//算法步骤:
//1.判断队列是否为满,若满则返回ERROR;
//2.将新元素插入队尾;
//3.队尾指针加1;
Status EnQueue(SqQueue &Q,char e){
if((Q.rear+1)%MAXSIZE==Q.front)
return ERROR; // 尾指针在循环意义上加1后等于头指针,表明队满
Q.base[Q.rear]=e; //新元素插在队尾上
Q.rear=(Q.rear+1)%MAXSIZE; //队尾指针加1
return OK;
}
//循环队列的出队
//算法步骤:
//1.判断队列是否为空,若空则返回ERROR;
//2.保存队头元素;
//3.队头指针加1;
Status DeQueue(SqQueue &Q,char &e){
if(Q.rear==Q.front)
return ERROR; //队空
e=Q.base[Q.front]; //保存队头元素
Q.front=(Q.front+1)%MAXSIZE; //队头指针加1
return OK;
}
//取队头元素
//算法步骤:
//当队列非空是,此操作返回当前队头元素,队头指针保持不变;
char GetHead(SqQueue Q){
if(Q.front!=Q.rear) //队列非空
return Q.base[Q.front]; //返回队头元素的值,对头指针保持不变
}
int main(){
SqQueue Q;
while(1){
int option=0;
char str;
system("cls");
cout<<"循环队列——队列的顺序表示和实现"<<endl;
cout<<"1.循环队列的初始化"<<endl;
cout<<"2.循环队列的入队"<<endl;
cout<<"3.循环队列的出队"<<endl;
cout<<"4.取出循环队列的头元素"<<endl;
cout<<"5.退出"<<endl;
cout<<"Please input your select:";
cin>>option;
switch(option){
case 1:
if(InitQueue(Q)==OK)
cout<<"1.Success!"<<endl;
else
cout<<"1.Error!"<<endl;
system("pause");
break;
case 2:
cout<<"Plesea input a char:";
cin>>str;
if(EnQueue(Q,str)==OK)
cout<<"2.Success!"<<endl;
else
cout<<"2.Error!"<<endl;
system("pause");
break;
case 3:
if(DeQueue(Q,str)==OK){
cout<<"3.Success!"<<endl;
cout<<"The char is "<<str<<endl;
}
else
cout<<"3.Error!"<<endl;
system("pause");
break;
case 4:
str=GetHead(Q);
cout<<"4.Success!"<<endl;
cout<<"4.The head char is "<<str<<endl;
system("pause");
break;
case 0:
exit(0);
break;
default:
cout<<"Warming!"<<endl;
break;
}
}
return 0;
}
数据结构——循环队列(队列的顺序表示和实现)
猜你喜欢
转载自blog.csdn.net/JEYMING/article/details/80054596
今日推荐
周排行