队列(c++ 数组实现)

可用具有N个元素的数组Q实现一个队列,front和rear分别表示队首和队尾,N表示数组的大小即队列的容量

初始状态:front=rear=0

如果反复对某个元素执行入队和出队操作,N次后,front=rear=N,此时向队列插入一个元素,就会发生数组越界错误,而此时队列中实际上没有元素,为了避免这个问题,令front和rear的下标在队列的末尾绕回,即把它看做“循环数组”可从Q[0]到Q[N-1],然后再回到Q[0]

计算队列种元素个数的公式:(N-front+rear)%N

注意一种情况:向队列插入N个对象,而不进行删除操作,用公式计算出队列的大小竟然为0,为了避免,可以规定Q最多存放N-1个对象。

代码:

#include<iostream>
using namespace std;
template<class Type>
class Queue{
private:
	int front;
	int rear;
	int MaxSize;
	Type *q;
public:
	Queue(int MSize):MaxSize(MSize){
		q=new Type[MaxSize];
		front=rear=0;
	}
	~Queue(){
		delete [] q;
	}
	int Size(){
		return (N-front+rear);
	}
	bool enQueue(const Type& item){
		if(Size()==N-1){
			cout<<"Queue is Full."<<endl;
			return false;
		}
		else{
			q[rear]=item;
			rear=(rear+1)%N;
			return true;
		}
	}
	bool deQueue(Type& item){
		if(Size()==0){
			cout<<"Queue is empty."<<endl;
			return false;
		}
		else{
			item=q[front];
			q[front]=NULL;
			front=(front+1)%N;
			return true;
		}
	}
};

int main(){
	Queue<int> q1;
	q1.enQueue(2);
	q1.enQueue(7);
	int t;
	q1.deQueue(t);
	cout<<t<<endl;
}

转载于:https://my.oschina.net/zshuangyan/blog/134336

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值