循环队列的基础操作(C++)

本文介绍了一种基于数组实现的循环队列结构,并详细解释了队列的基本操作,包括插入、删除、遍历等。此外,还提供了完整的C++代码实现示例,帮助读者更好地理解和掌握循环队列的工作原理。
#include "iostream"
#include"LinkQueue.h"

using namespace std;

//===================队列(先进先出)=============
/*只允许在队尾进行插入操作,而在队头进行删除操作的线性表*/

//==============循环队列(头尾相接)===========
/*队列:数组+两个指针*/
const int MAXSIZE = 20;

struct SqQueue
{
	int val[MAXSIZE];
	int front;//头指针
	int reat;//尾指针,若队列不空,指向队列尾元素的下一个位置
	struct SqQueue(int x) :front(x), reat(x){};
};

//判断队列长度
int QueueLength(const SqQueue *Q)
{
	return (Q->reat - Q->front + MAXSIZE) % MAXSIZE;
}

//队列的遍历
bool VisitQueue(const SqQueue *Q)
{
	if ((Q->reat + 1) % MAXSIZE == Q->front)
		return false;
	int i = Q->front;
	while (i != Q->reat)
	{
		cout << Q->val[i] << " ";
		i = (i + 1) % MAXSIZE;
	}
	cout << endl;
	return true;
}

//队列的插入
bool QueueInsert(SqQueue *Q, int data)
{
	if ((Q->reat + 1) % MAXSIZE == Q->front)/* 队列满的判断 */
	{
		cout << "满队!" << endl;
		return false;
	}
	else
	{
		Q->val[Q->reat] = data; /* 将data赋值给队尾 */
		Q->reat = (Q->reat + 1) % MAXSIZE;/* rear指针向后移一位置,若到最后则转到数组头部 */

		return true;
	}
}

//队列的删除
bool QueueDelete(SqQueue *Q)
{
	if ((Q->reat + 1) % MAXSIZE == Q->front)/* 队列空的判断 */
	{
		cout << "空队" << endl;
		return false;
	}
	else
	{
		Q->front = (Q->front + 1) % MAXSIZE;/* front指针向后移一位置, 若到最后则转到数组头部 */

		return true;
	}
}

//队列清空
bool ClearQueue(SqQueue *Q)
{
	Q->front = Q->reat = 0;
	return true;
}

//判断队列是否为空
bool QueueEmpty(SqQueue *Q)
{
	if ((Q->reat + 1) % MAXSIZE == Q->front)
		return true;
	else
		return false;
}





int main()
{
	=========循环队列=============
	SqQueue *Q = new SqQueue(0);
	int n;
	while (cin >> n)
		QueueInsert(Q, n);

	//QueueDelete(Q);
	VisitQueue(Q);


	system("pause");// 或者 getchar();

	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值