循环队列【10】

/*
	2011.09.06
	循环队列的实现
	*/

#include<iostream>
#include<malloc.h>
using namespace std;

#define MAXQSIZE 5
#define OK             1
#define ERROR       0
#define OVERFLOW 0

typedef int Status;
typedef int QElemType;
typedef struct {
	QElemType *base;//初始化的动态分配存储空间
	int front;
	int rear;
}SqQueue;

Status InitQueue( SqQueue &Q ){
	//初始化一个空的循环队列
	Q.base = ( QElemType * ) malloc ( MAXQSIZE * sizeof( QElemType ) );
	Q.front = Q.rear = 0;
	return OK;
}

Status QueueLength( SqQueue Q ){
	//返回Q的元素个数,即队列的长度
	return ( Q.rear - Q.front + MAXQSIZE ) % MAXQSIZE;
}

Status EnQueue( SqQueue &Q, QElemType e ){//数组最后留了一个空间,易于判断,队列是否为满
	//插入元素e为Q的新的队尾元素
	cout <<e <<endl;
	if( ( Q.rear + 1 )  % MAXQSIZE == Q.front ) return ERROR;//队列满
	Q.base[ Q.rear ] = e;
	
	Q.rear = ( Q.rear + 1 ) % MAXQSIZE;
	return OK;
}

Status DeQueue( SqQueue &Q, QElemType e ){
	//若队列不空,则删除Q的对头元素,用e返回其值,并返回OK
	//否则返回ERROR
	if( Q.front == Q.rear ) return ERROR;
	e = Q.base[ Q.front ];
	Q.front = ( Q.front + 1 ) % MAXQSIZE;
	return OK;
}

int main()
{
	SqQueue queue;
	InitQueue( queue );
	for( int i = 0; i < 3; i++ ){
		EnQueue( queue,i );
	}

	cout << "队列长度为:"<< QueueLength( queue ) << endl;
	for( int i = 0; i < 3; i++){
		cout << queue.base[ i ] <<"、";
	}


	system("pause");
	return 0;
}


注意事项:在判断队列为满的时候,特意在数组最后留了一个空间,便于确认队列是否为满?

 

第二种方法:运用flag标记吧。~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值