- 初始化队列q;
- 判断队列q是否为空;
- 依次进队元素a,b,c;
- 出队一个元素,输出该元素;
- 依次进队元素d,e,f;
- 输出出队序列;
- 释放队列。
#include<iostream>
using namespace std;
#define Maxsize 50
typedef char ElemType;
typedef struct
{
ElemType data[Maxsize];
int front,rear;
}SqQueue;
//初始化队列
void InitQueue(SqQueue *&q)
{
q=(SqQueue *)malloc(sizeof(SqQueue));
q->front=q->rear=0;
}
//判断队列是否为空
bool QueueEmpty(SqQueue *q)
{
return (q->front==q->rear);
}
//进队元素
bool enQueue(SqQueue *&q,ElemType e)
{
if((q->rear+1)%Maxsize==q->front)
return false;
q->rear=(q->rear+1)%Maxsize;
q->data[q->rear]=e;
return true;
}
//出队元素
bool deQueue(SqQueue *&q,ElemType &e)
{
if(q->front==q->rear)
return false;
q->front=(q->front+1)%Maxsize;
e=q->data[q->front];
return true;
}
//销毁队列
void DestoryQueue(SqQueue *&q)
{
free(q);
}
//主函数
int main()
{
SqQueue *q;ElemType w;
cout<<"初始化环形队列"<<endl;
InitQueue(q);
if(QueueEmpty(q)==1) cout<<"队列为空"<<endl;
else cout<<"队列不为空"<<endl;
cout<<"依次进队元素a,b,c"<<endl;
if(!enQueue(q,'a'))
cout<<"队满,不能进队"<<endl;
if(!enQueue(q,'b'))
cout<<"队满,不能进队"<<endl;
if(!enQueue(q,'c'))
cout<<"队满,不能进队"<<endl;
if(QueueEmpty(q)==1) cout<<"队列为空"<<endl;
else cout<<"队列不为空"<<endl;
if(deQueue(q,w)==0)
cout<<"队空,不能出列"<<endl;
else cout<<"出队一个元素,输出该元素:"<<w<<endl;
cout<<"依次进队元素d,e,f"<<endl;
if(!enQueue(q,'d'))
cout<<"队满,不能进队"<<endl;
if(!enQueue(q,'e'))
cout<<"队满,不能进队"<<endl;
if(!enQueue(q,'f'))
cout<<"队满,不能进队"<<endl;
cout<<"输出出队序列:"<<endl;
while(!QueueEmpty(q))
{
deQueue(q,w);
cout<<w<<" ";
}
cout<<endl;
cout<<"释放队列"<<endl;
DestoryQueue(q);
return 0;
}