#include <iostream>
#include <malloc.h>
#include <stdlib.h>
using namespace std;
#define MaxSize 5
typedef int ElemType;
typedef bool Status;
typedef struct
{
ElemType *arr;
ElemType front;
ElemType rear;
}Queue;
void Init(Queue*);
Status EnQueue(Queue*,ElemType);
Status DeQueue(Queue*,ElemType*);
Status IsEmpty(Queue*);
int QueueLenth(Queue*);
void Traverse(Queue*);
Status IsFull(Queue*);
int main()
{
Queue q;int val;
//队列初始化
Init(&q);
//判断队列是否为空
if(IsEmpty(&q))cout<<"The queue is empty"<<endl<<endl;
else cout<<"The queue is not empty"<<endl;
//元素入队 1,2,3,4,5
if(EnQueue(&q,1));cout<<"The number successfully entry the queue"<<endl;
if(EnQueue(&q,2));cout<<"The number successfully entry the queue"<<endl;
if(EnQueue(&q,3));cout<<"The number successfully entry the queue"<<endl;
if(EnQueue(&q,4));cout<<"The number successfully entry the queue"<<endl<<endl;
//遍历队列
Traverse(&q);
//判断队满入队的情况
if(!EnQueue(&q,5))cout<<"The number unsuccessfully entry the queue"<<endl<<endl;
//出队
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
Traverse(&q);
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
Traverse(&q);
//判断空队列出队的情况
if(DeQueue(&q,&val))cout<<"The number is "<<val<<"."<<endl;
//求队列的长度
int len=QueueLenth(&q);
cout<<"The lenth of queue is "<<len<<"."<<endl;
}
void Init(Queue* q)
{
q->arr=(ElemType*)malloc(sizeof(ElemType)*MaxSize);
if(q->arr==0)exit(-1);
q->front=0;
q->rear=0;
cout<<"Initiating successful"<<endl;
}
Status IsEmpty(Queue* q)
{
if(q->front==q->rear)return true;
else return false;
}
void Traverse(Queue* q)
{
ElemType i=q->front;
if(i==q->rear)cout<<"The queue is empty"<<endl;
while(i!=q->rear)
{
cout<<q->arr[i]<<" ";
i=(i+1)%MaxSize;
}
cout<<endl;
return;
}
int QueueLenth(Queue* q)
{
return ((q->rear-q->front+MaxSize)%MaxSize);
}
Status EnQueue(Queue* q,ElemType val)
{
if(IsFull(q))return false;
else
{
q->arr[q->rear]=val;
q->arr[q->rear]=val;
q->rear=(q->rear+1)%MaxSize;
return true;
}
}
Status DeQueue(Queue* q,ElemType* val)
{
if(IsEmpty(q))return false;
else
{
*val=q->arr[q->front];
q->front=(q->front+1)%MaxSize;
return true;
}
}
Status IsFull(Queue* q)
{
if((q->rear+1)%MaxSize==q->front)return true;
else return false;
}
顺序队列的一系列操作
最新推荐文章于 2024-10-25 18:01:58 发布