顺序队列的一系列操作

#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;
}

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值