//循环队列的基本操作
#define MAXQSIZE 16
#include <iostream>
using namespace std;
typedef int elementype;
//定义队列
typedef struct{
elementype *pbase;
elementype front;
elementype rear;
}QueueLinkList;
bool initQueueLinkList(QueueLinkList &Q);//初始化队列
bool creatQueueLinkList(QueueLinkList &Q);//创建队列
bool addQueueLinkList(QueueLinkList &Q,int e);//入队
bool deleteQueueLinkList1(QueueLinkList &Q);//出队
int deleteQueueLinkList2(QueueLinkList &Q);//出队,并返回删除的元素值
bool isEmptyQueueLinkList(QueueLinkList &Q);//判断队列是否为空
bool isFullQueueLinkList(QueueLinkList &Q);//判断队列是否为满
void traversQueueLinkList(QueueLinkList &Q);//遍历队列
bool destroyQueueLinkList(QueueLinkList &Q);//销毁队列
int main(){
QueueLinkList m;
int a = initQueueLinkList(m);
if(a)
cout << "初始化队列成功" << endl;
a = creatQueueLinkList(m);
if(a)
cout << "创建队列成功" << endl;
traversQueueLinkList(m);
int n;
cout << "请输入要入队的元素" << endl;
cin >> n;
a = addQueueLinkList(m,n);
if(a)
cout << "入队成功" << endl;
traversQueueLinkList(m);
a = deleteQueueLinkList1(m);
if(a)
cout << "出队成功" << endl;
traversQueueLinkList(m);
elementype b = deleteQueueLinkList2(m);
cout << "出队成功,出队元素为 " << b << endl;
traversQueueLinkList(m);
a = destroyQueueLinkList(m);
if(a)
cout << "销毁队列成功" << endl;
return 0;
}
//初始化队列
bool initQueueLinkList(QueueLinkList &Q){
Q.pbase = new int[MAXQSIZE];
if(Q.pbase == NULL){
cout << "动态内存分配失败" << endl;
exit(-1);
}
Q.front = Q.rear = 0;
return true;
}
//创建队列
bool creatQueueLinkList(QueueLinkList &Q){
int i;
cout << "请输入要输入的元素值个数" << endl;
cin >> i;
cout << "请输入要输入的元素值" << endl;
for(int j=0;j<i;j++){
elementype n;
cin >> n;
addQueueLinkList(Q,n);
}
return true;
}
//入队
bool addQueueLinkList(QueueLinkList &Q,int e){
if(isFullQueueLinkList(Q)){
cout << "队列已满,入队操作不能执行" << endl;
exit(-1);
}
Q.pbase[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXQSIZE;
return true;
}
//出队
bool deleteQueueLinkList1(QueueLinkList &Q){
if(isEmptyQueueLinkList(Q)){
cout << "队列为空,出队操作不能执行" << endl;
exit(-1);
}
Q.front = (Q.front + 1) % MAXQSIZE;
return true;
}
//出队,并返回删除的元素值
int deleteQueueLinkList2(QueueLinkList &Q){
if(isEmptyQueueLinkList(Q)){
cout << "队列为空,出队操作不能执行";
exit(-1);
}
elementype e = Q.pbase[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return e;
}
//判断队列是否为空
bool isEmptyQueueLinkList(QueueLinkList &Q){
if(Q.pbase[Q.front] == Q.pbase[Q.rear])
return true;
return false;
}
//判断队列是否为满
bool isFullQueueLinkList(QueueLinkList &Q){
if(Q.pbase[Q.front] == Q.pbase[Q.rear+1])
return true;
return false;
}
//遍历队列
void traversQueueLinkList(QueueLinkList &Q){
if(isEmptyQueueLinkList(Q)){
cout << "队列为空,不能遍历" << endl;
exit(-1);
}
cout << "遍历队列为" << endl;
elementype i = Q.front;
while(i!=Q.rear)
{
cout << Q.pbase[i] << " ";
i=(i+1)%MAXQSIZE;
}
cout << endl;
}
//销毁队列
bool destroyQueueLinkList(QueueLinkList &Q){
if(Q.pbase)
delete Q.pbase;
Q.pbase = NULL;
Q.front = 0;
Q.rear = 0;
return true;
}
循环队列的基本操作
最新推荐文章于 2024-07-03 20:18:43 发布