循环队列的实现

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值