2021-11-10
作者:互联网
顺序循环队列
基本操作
1.初始化
2.入队
3.出队
4.取对头元素
5.遍历
#include<iostream>
using namespace std;
#define ok 1
#define error 0
#define MAXSIZE 100
//定义循环队列结构
struct SqQueue {
int *base;
int front;
int rear;
};
//初始化循环队列
int Init(SqQueue &Q){
Q.base = new int[MAXSIZE];
if(!Q.base){
exit(error);
}
Q.front = Q.rear = 0;
return ok;
}
//求循环队列长度
int QueueLength(SqQueue Q){
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
//入队
int Insert(SqQueue &Q , int e){
//队列已满,不能入队
if((Q.rear + 1) % MAXSIZE == Q.front){
return error;
}
Q.base[Q.rear] = e;
Q.rear =(Q.rear + 1) % MAXSIZE;
return ok;
}
//出队,引用e接收出队的数据
int DeQueue(SqQueue &Q, int &e){
//队空
if(Q.rear == Q.front){
return error;
}
e = Q.base[Q.front];
//队头指针+1
Q.front = (Q.front + 1) % MAXSIZE;
return ok;
}
//取对头
int GetHead(SqQueue Q){
if(Q.front != Q.rear){
return Q.base[Q.front];
}
}
//遍历循环队列
void print(SqQueue Q){
while(Q.front != Q.rear){
cout<<Q.base[Q.front]<<",";
Q.front = (Q.front + 1) % MAXSIZE;
}
}
int main(){
int data;
SqQueue Q;
Init(Q);
cout<<"----------入队---------------\n";
for(int i=1; i<=5; i++){
Insert(Q,i);
}
print(Q);
cout<<"\n----------出队---------------\n";
DeQueue(Q,data);
cout<<"出队元素为: "<<data<<endl;
print(Q);
cout<<"\n----------取对头元素---------------\n";
cout<<"对头元素为:"<<GetHead(Q)<<endl;
return 0;
}
标签:11,10,return,int,SqQueue,MAXSIZE,2021,front,rear 来源: https://blog.csdn.net/weixin_44865810/article/details/121257216