顺序队列的实现

 

/************************************************************************/
/*                      队列的环式顺序实现                              */
/************************************************************************/
#include <STDIO.H>
#include <STDLIB.H>


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));

	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]);
	}
}




void 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");
	/*溢出测试*/
	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));
}








/*实验结果如下*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值