顺序队列(可循坏利用的顺序循坏队列) ——以C语言为例

实现循环队列,避免假溢出等问题

			 //顺序队列
 #include <stdio.h>
 #include <iostream>
 using namespace std;
 #define qElemType int 
 #define QUEUE_INIT_SIZE 5
 typedef struct sqQueue{
 	qElemType *elem;//队列首地址 
 	int front;//队头下标 
 	int rear;//队尾下标 
 }; 
 //判空函数 
 int isEmpty(sqQueue Q){
 	return Q.front==Q.rear;
 }
//判满函数 
 int isFull(sqQueue Q){
 	return (Q.rear+1)%QUEUE_INIT_SIZE==Q.front;
 	//少保存一个队列元素;
	//为了解决判空条件与判满条件出现矛盾
 }
 void initSqQueue(sqQueue &Q){
 
 	//创建一个队列数组 
 	Q.elem=new qElemType[QUEUE_INIT_SIZE];
 	Q.rear=0;
 	Q.front=0;
 }
 //向队列插入元素函数 
 void enQueue(sqQueue &Q,qElemType e){
 	//先判断队列是否已满
	 if(isFull(Q)){
	 	cout<<"当前队列已满,不能再增加队列元素"<<endl;
	 	return;
	 }
	 Q.elem[Q.rear]=e;
	 Q.rear=(Q.rear+1)%QUEUE_INIT_SIZE;
	 //解决假溢出的现象 
	 
 } 
 //向队列删除元素函数
 void deQueue(sqQueue &Q,qElemType &e){
 	//先判断队列是否为空
	 if(isEmpty(Q)){
	 	cout<<"当前队列已空,不能再删除队列元素"<<endl;
	 	return ; 
	}
	e=Q.elem[Q.front];
	Q.front=(Q.front+1)%QUEUE_INIT_SIZE;
	//解决了避免出现Q.elem[-1]的现象 
 } 
 //打印队列队头队尾元素
 void printFrontAndRear(sqQueue Q){
 	if(isEmpty(Q)){
 		cout<<"当前队列已空,不能打印队列元素"<<endl;
 		return ;
	 }
	 cout<<"队头为"<<Q.elem[Q.front]<<endl;
	 cout<<"队尾为"<<Q.elem[(Q.rear-1+QUEUE_INIT_SIZE)%QUEUE_INIT_SIZE]<<endl;
 } 
 int main(){
 	sqQueue Q;
 	initSqQueue(Q);
 	enQueue(Q,10);
 	enQueue(Q,20);
 	enQueue(Q,30);
 	enQueue(Q,40);
 	enQueue(Q,50);
 	enQueue(Q,60);
 	printFrontAndRear(Q);
 	qElemType e;
 	deQueue(Q,e);
 	deQueue(Q,e);
 	printFrontAndRear(Q);
 	deQueue(Q,e);
 	deQueue(Q,e);
 	cout<<"被删除的队列元素为:"<<e<<endl;
 	deQueue(Q,e);
 	deQueue(Q,e);
 }
 在这里插入代码片

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值