实现队列的初始化、入队列、出队列、判断队列是否为空、求队列长度和输出显示队列元素C++总代码
时间: 2023-12-24 18:24:45 浏览: 49
```cpp
//初始化队列
#include<iostream>
using namespace std;
#define MAXSIZE 100
typedef struct{
int data[MAXSIZE];
int front,rear;
}SqQueue;
void InitQueue(SqQueue &Q){
Q.front=Q.rear=0;
}
//判断队列是否为空
bool QueueEmpty(SqQueue Q){
if(Q.front==Q.rear)
return true;
else
return false;
}
//求队列长度
int QueueLength(SqQueue Q){
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
//入队列
bool EnQueue(SqQueue &Q,int x){
if((Q.rear+1)%MAXSIZE==Q.front)
return false;
Q.data[Q.rear]=x;
Q.rear=(Q.rear+1)%MAXSIZE;
return true;
}
//出队列
bool DeQueue(SqQueue &Q,int &x){
if(Q.front==Q.rear)
return false;
x=Q.data[Q.front];
Q.front=(Q.front+1)%MAXSIZE;
return true;
}
//输出队列元素
void PrintQueue(SqQueue Q){
while(Q.front!=Q.rear){
cout<<Q.data[Q.front]<<" ";
Q.front=(Q.front+1)%MAXSIZE;
}
cout<<endl;
}
int main(){
SqQueue Q;
InitQueue(Q);
if(QueueEmpty(Q))
cout<<"队列为空"<<endl;
else
cout<<"队列不为空"<<endl;
EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
EnQueue(Q,4);
EnQueue(Q,5);
cout<<"队列长度为:"<<QueueLength(Q)<<endl;
cout<<"队列元素为:";
PrintQueue(Q);
int x;
DeQueue(Q,x);
cout<<"出队列元素为:"<<x<<endl;
cout<<"队列长度为:"<<QueueLength(Q)<<endl;
cout<<"队列元素为:";
PrintQueue(Q);
return 0;
}
```