数据结构之循环队列

#include<iostream>
using namespace std;
#define QSIZE 8
typedef int ElemType;
typedef struct {
	ElemType *pBase;
	int Front;
	int Rear;
}Queue;//循环队列比顺序对要节省大量的空间,默认是不用顺序队的
void InitQueue(Queue &Q)
{
	Q.pBase = new ElemType[QSIZE];
	Q.Front = 0;
	Q.Rear = 0;
}
void DestroyQueue(Queue &Q)
{
	delete[]Q.pBase;
	Q.Front = 0;
	Q.Rear = 0;
	return;
}
void ClearQueue(Queue &Q)
{
	Q.Front = 0;
	Q.Rear = 0;
	return;
}
bool QueueFull(Queue &Q)//浪费一个单元为代价,当处理大量的数据时是非常值得的.
{
	if ((Q.Rear + 1) % QSIZE == Q.Front)
		return true;
	else
		return false;
}
bool QueueEmpty(Queue &Q)
{
	if (Q.Front == Q.Rear)
		return true;
	else
		return false;
}
int QueueLength(Queue &Q)
{
	if (QueueEmpty(Q))
		return 0;
	else
		return (Q.Rear - Q.Front + QSIZE) % QSIZE;
}
bool GetHead(Queue Q, ElemType &e)
{
	if (QueueEmpty(Q))
		return false;
	e = Q.pBase[Q.Front];
	return true;
}
bool EnQueue(Queue &Q, ElemType e)
{
	if (QueueFull(Q))
		return false;
	Q.pBase[Q.Rear] = e;
	Q.Rear = (Q.Rear + 1) % QSIZE;
	return true;
}
bool DeQueue(Queue &Q, ElemType &e)
{
	if (QueueEmpty(Q))
		return false;
	e = Q.pBase[Q.Front];
	Q.Front = (Q.Front + 1) % QSIZE;
	return true;
}
void Visit(ElemType e)
{
	cout << e << " ";
}
void Traverse(Queue Q)
{
	int i = Q.Front;
	while (i != Q.Rear)
	{
		Visit(Q.pBase[i]);
		i = (i + 1) % QSIZE;
	}
	cout << endl;
	return;
}
int main(void)
{
	Queue Q;
	ElemType e = 0;
	InitQueue(Q);
	EnQueue(Q, 1);
	EnQueue(Q, 2);
	EnQueue(Q, 3);
	EnQueue(Q, 4);
	EnQueue(Q, 5);
	EnQueue(Q, 6);
	GetHead(Q, e);
	cout << e << endl;
	Traverse(Q);
	if (QueueEmpty(Q))
		cout << "Indeed Empty!" << endl;
	else
		cout << "Not Empty!" << endl;
	cout << QueueLength(Q) << endl;
	EnQueue(Q, 7);
	//注意:7个数据则队便满,EnQueue(Q, 8)无效
	if (QueueFull(Q))
		cout << "Indeed Full!" << endl;
	else
		cout << "Not Full!" << endl;
	Traverse(Q);
	DeQueue(Q, e);
	cout << e << endl;
	Traverse(Q);
	return(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值