c语言:循环队列的实现

时间:2023-01-27 17:36:48
#include<iostream>
#include<stdio.h>
#include<math.h>
#define QUEUE_MAX_SIZE 100
using namespace std;
typedef struct Sqqueue
{
int *data;
int front;
int rear;
}Sqqueue;
//函数声明
void Error(char *s); //错误处理函数
void Destroy_Sqqueue(Sqqueue &q);//销毁循环队列函数
void Clear_Sqqueue(Sqqueue &q);//清除循环队列函数
int Getlength_Sqqueue(Sqqueue &q);//得到循环队列的长度
void Gethead_Sqqueue(Sqqueue &q, int e);//取循环队列的对头元素
void En_Sqqueue(Sqqueue &q, int e);//入队操作
void De_Sqqueue(Sqqueue &q, int e);//出队操作
Sqqueue Creat_Sqqueue();//创建一个循环队列
void Print_Sqqueue(Sqqueue &q);//以此输出循环队列的值
//函数定义
void Error(char *s)
{
cout << s << endl;
exit(1);
}
Sqqueue Creat_Sqqueue()
{
Sqqueue q;
q.data = new int[QUEUE_MAX_SIZE];
if (!q.data)
Error("存储分配失败!");
q.front = q.rear = 0;
int length = 0;
int number = 0;
cout << "请输入循环队列的长度:";
cin >> length;
cout << "请输入循环队列的值:";
for (int i = 0; i < length; i++)
{
cin >> number;
q.data[q.rear] = number;
q.rear = (q.rear + 1) % QUEUE_MAX_SIZE;
}
return q;
}
void Destroy_Sqqueue(Sqqueue &q)
{
delete[] q.data;
q.front = q.rear = 0;
cout << "该循环队列销毁成功!";
}
void Clear_Sqqueue(Sqqueue &q)
{
q.front = q.rear = 0;
}
int Getlength_Sqqueue(Sqqueue &q)
{
int Queuelength = (q.rear - q.front + QUEUE_MAX_SIZE) % QUEUE_MAX_SIZE;
return Queuelength;
}
void Gethead_Sqqueue(Sqqueue &q,int e)
{
if (q.rear == q.front)
Error("该循环队列为空!");
e = q.data[q.front];
cout << "该循环队列的队头元素是:" << e << endl;
}
void En_Sqqueue(Sqqueue &q, int e)
{
if (((q.rear + 1) % QUEUE_MAX_SIZE) == q.front)
Error("该循环队列已满!");
q.data[q.rear] = e;
q.rear = (q.rear + 1) % QUEUE_MAX_SIZE;
}
void De_Sqqueue(Sqqueue &q, int e)
{
if (q.front == q.rear)
Error("该循环队列为空队列!");
e = q.data[q.front];
q.front = (q.front + 1) % QUEUE_MAX_SIZE;
cout << "出队的元素是:" << e << endl;
}
void Print_Sqqueue(Sqqueue &q)
{
cout << "该循环队列的元素是:";
while (q.front != q.rear)
{
cout << q.data[q.front] << " ";
q.front = (q.front + 1) % QUEUE_MAX_SIZE;
}
cout << endl;
}

int main()
{
Sqqueue Q;
int e = 0;
Q = Creat_Sqqueue();
cout << "该循环队列的长度是:"<<Getlength_Sqqueue(Q) << endl;
Gethead_Sqqueue(Q, e);
cout << "请输入要入队的元素:";
cin >> e;
En_Sqqueue(Q, e);
De_Sqqueue(Q, e);
Print_Sqqueue(Q);
return 0;
}