队列的顺序表示与实现

#include <iostream>
using namespace std;

#define QElemType int

#define OK 1
#define FALSE 0
#define TRUE 1
#define ERROR 0

// 循环队列,队列的顺序存储结构

#define MAXQSIZE 100	//最大队列长度
typedef struct
{
	QElemType *base;		//初始化的动态分配存储空间
	int Front;				//头指针,若队列不空,指向队列头元素
	int Rear;				//尾指针,若队列不空,指向队列尾元素的下一个位置
}SqQueue;


//构造一个空队列Q
int InitQueue(SqQueue &Q)
{
	Q.base = (QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
	if(!Q.base)
		exit(OVERFLOW);
	Q.Front = Q.Rear = 0;
	return OK;
}


//插入元素e为Q的新的队列元素
int EnQueue(SqQueue &Q,QElemType e)
{
	if((Q.Rear + 1) % MAXQSIZE == Q.Front)	//队列满
		return ERROR;
	Q.base[Q.Rear] = e;
	Q.Rear = (Q.Rear + 1) % MAXQSIZE;
	return OK;
}

//输出队列Q中的元素
void QueueTraverse(SqQueue Q)
{
	if(Q.Front == Q.Rear)
		cout << "队列为空" << endl;
	while(Q.Front != Q.Rear)
	{
		cout << Q.base[Q.Front ]<<" ";
		Q.Front = (++Q.Front) % MAXQSIZE;
	}
	cout << endl;
}

//若队列为空,则返回TRUE 
//否则,返回FALSE
int QueueEmpty(SqQueue Q)
{
	if(Q.Rear == Q.Front)
		return TRUE;
	else
		return FALSE;
}


//得到队列Q的长度
int QueueLength(SqQueue Q)
{
	int i = 0;
	while(Q.Front != Q.Rear)
	{
		++i;
		++Q.Front;
	}

	return i;

}

//若队列不空,用e返回队头指针
void GetHead(SqQueue Q,QElemType &e)
{
	if(Q.Front == Q.Rear)
		cout << "队列空!" <<endl;
	e = Q.base[Q.Front];
}

//若队列不空,则用e返回Q的队头元素
void DeQueue(SqQueue &Q,QElemType &e)
{
	if(Q.Front == Q.Rear)
		cout << "队列空!" << endl;
	e = Q.base[Q.Front];
	Q.Front = (Q.Front+1) % MAXQSIZE;
}

//销毁队列Q,Q不再存在
void DestroyQueue(SqQueue &Q)
{
	if(Q.Front != Q.Rear)
	{
		free(Q.base);
		Q.Front++;
	}
	cout << "队列不再存在!"<< endl;
}

//将队列Q清为空队列
void ClearQueue(SqQueue &Q)
{
	while(Q.Front != Q.Rear)
	{
		Q.base[Q.Front] = NULL;
		Q.Front++;
	}
	Q.Front = Q.Rear = 0;
}

void main()
{
	SqQueue Q;
	InitQueue(Q);

	QElemType a = 10;
	EnQueue(Q,a);
	QElemType b = 11;
	EnQueue(Q,b);
	QueueTraverse(Q);



	cout << QueueEmpty(Q) << endl;
	//cout << QueueLength(Q) << endl;

	//QElemType c;
	//GetHead(Q,c);
	//cout << c << endl;


	//QElemType d;
	//DeQueue(Q,d);
	//cout << d << endl;
	//QueueTraverse(Q);

	//DestroyQueue(Q);
	//QueueTraverse(Q);

	ClearQueue(Q);
	//QueueTraverse(Q);

	system("pause");
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值