#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
typedef int QElementType;
typedef int status;
#define _ERROR 0
#define _OK 1
#define MAXQSIZE 10
//队列的数据抽象
typedef struct
{
QElementType *base;//这里相当于存储数据的数组,只不过我这里是动态分配存储空间,一个连续的存储空间
int front;//队列头指针
int rear;//队列尾指针
}SqQueue;
//队列初始化函数
status InitQueue(SqQueue &Q)
{
Q.base = (QElementType*)malloc(MAXQSIZE * sizeof(QElementType));//分配了一个连续的整型地址,由base指针指向其首地址
if (Q.base == NULL)
return _ERROR;
Q.front = Q.rear = 0;
return _OK;
}
//判断队列是否为空
bool IsEmpty(SqQueue Q)
{
return Q.front == Q.rear;
}
//判断队列是否已满,这里我们牺牲一个空间,为什么?你懂的
bool IsFull(SqQueue Q)
{
return ((Q.rear + 1) % MAXQSIZE) == Q.front;
}
//获取队列长度
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
//入队列
status InQueue(SqQueue &Q, QElementType e)
{
//判断队列是否已满
if (IsFull(Q))
return _ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return _OK;
}
//出队列
status OutQueue(SqQueue &Q, QElementType &e)//这里是引用,不是取地址
{
//判断队列是否为空
if (IsEmpty(Q))
return _ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return _OK;
}
//打印队列中的元素
void PrintQueue(SqQueue Q)
{
for (int i = Q.front; i%MAXQSIZE < Q.rear; i++)
{
printf("%d\n", Q.base[i]);
}
}
//取队头元素
bool GetFront(SqQueue &Q, QElementType &e)
{
if (IsEmpty(Q))
return _ERROR;
e = Q.base[Q.front];
return _OK;
}
int main()
{
//初始化队列
SqQueue Q;
InitQueue(Q);
printf("入队列测试:\n");
//入队列测试
InQueue(Q, 1);
InQueue(Q, 2);
InQueue(Q, 3);
InQueue(Q, 4);
InQueue(Q, 5);
InQueue(Q, 6);
InQueue(Q, 7);
InQueue(Q, 8);
InQueue(Q, 9);
PrintQueue(Q);
printf("取队头元素:\n");
//取队头元素测试
QElementType e1;
GetFront(Q, e1);
printf("%d\n", e1);
printf("溢出测试:\n");
//溢出测试
InQueue(Q, 10);
PrintQueue(Q);
printf("出队列测试:\n");
//出队列测试
QElementType e;
OutQueue(Q, e);
printf("%d\n", e);
OutQueue(Q, e);
printf("%d\n", e);
printf("长度测试:\n");
//长度测试
printf("%d\n", QueueLength(Q));
system("pause");
return 0;
}
循环队列的实现
最新推荐文章于 2022-07-19 15:26:21 发布