C_循环队列

循环队列

#include <iostream>
using namespace std;

//循环队列 

#define OK 1
#define FALSE 0
#define ERROR -1
#define OVERFLOW -2 

 
#define MAXQSIZE 100//最大队列长度 

typedef int QElemType;
typedef int Status;


//构建循环队列结构 
typedef struct{
	QElemType *base;//初始化的动态分配存储空间
	int front;//头指针
	int rear;//尾指针 
} SqQueue;

//初始化循环队列 
Status InitQueue(SqQueue &Q){
	Q.base=new QElemType[MAXQSIZE];//创建循环队列 
	if(!Q.base)
		return ERROR;
	Q.front=Q.rear=0;//初始化 
	return OK;
}

//求队列长度 
int QueueLength(SqQueue Q){ 
	return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

//循环队列入队 
Status EnQueue(SqQueue &Q,QElemType e){
	if((Q.rear+1)%MAXQSIZE==Q.front)//满队 
		return OVERFLOW;
	Q.base[Q.rear]=e;
	Q.rear=(Q.rear+1)%MAXQSIZE;
	return OK; 
}

//循环队列出队 
Status DeQueue(SqQueue &Q,QElemType &e){
	if(Q.front==Q.rear)//队空 
		return ERROR; 
	e=Q.base[Q.front];
	Q.front=(Q.front+1)%MAXQSIZE;
	return OK;
}

//简单遍历(取循环队中某个位置的元素) 
void tra(SqQueue Q){
	cout<<Q.base[Q.front+2];
} 

//遍历循环队列 
//void TraverseQueue(SqQueue Q){
//	QElemType *p;
//	q=Q.base[Q.front];
//	while(q!=){
//		
//	}
//} 

int main(){
	int i,n;
	SqQueue Q;
	QElemType e;
	if(InitQueue(Q)==OK)
		cout<<"循环队列创建成功!\n\n";
	else
	{
		cout<<"循环队列创建失败";
		return ERROR;
	}
	cout<<"请输入循环队列的数据长度:";
	cin>>n;
	cout<<"请输入循环队列的数据元素:" ; 
	for(i=1;i<=n;i++){
		cin>>e;
		EnQueue(Q,e);
	}
	
	cout<<"循环队列的输出为:";
	while(DeQueue(Q,e)==OK){
		 cout<<e<<" ";
	} 
	
	cout<<"\n循环队列输出完毕!"; 
	delete Q.base;
	
//	这是遍历代码检测使用的 
//	cout<<"a:";
//	tra(Q);
//	cout<<endl;
//	
//	cout<<"b:";
//	DeQueue(Q,e);
//	cout<<e<<endl;
//	
//	cout<<"c:";
//	tra(Q);
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值