实现循环队列,避免假溢出等问题
//顺序队列
#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);
}
在这里插入代码片
运行结果: