数据结构教程—循环队列顺序存储结构C++模板类实现

类定义:

#include<iostream>
#define MaxSize 4
using namespace std;

template<class ElemType>
class Queue{
private:
	ElemType *data;
	int front, rear;//front队头指针 rear队尾指针
public:
	Queue();//无参构造
	~Queue();

	bool QueueEmpty();//对空
	bool QueueFull();//队满
	bool enQueue(ElemType e);//进队列
	bool deQueue(ElemType&e);//出队列

	void DispQueue();//输出队列
};

类中各函数:


template<class ElemType>
Queue<ElemType>::Queue() {
	this->data = new ElemType[MaxSize];//使用该语句为数组分配空间!!!
	front = 0;//在循环队列时使用front=rear=0的方式,而不是用front=-1,因为front=-1将导致(this->rear+1)%MaxSize==this->front(判断栈满)永远不成立
	rear = 0;
}
template<class ElemType>
Queue<ElemType>::~Queue() {
	if (this->data == NULL) {
		return;
	}
	delete this->data;
//队空
}template<class ElemType>
bool Queue<ElemType>::QueueEmpty() {
	return this->front == this->rear;//判空语句
}
//队满
template<class ElemType>
bool Queue<ElemType>::QueueFull() {
	return (this->rear+1)%MaxSize==this->front;//队满判断语句
}
//进队列
template<class ElemType>
bool Queue<ElemType>::enQueue(ElemType e) {
	if (this->QueueFull()) {//队列满则无法进队列
		cout << "is Full" << endl;
		return false;
	}		
	this->rear = (this->rear + 1) % MaxSize;
	this->data[this->rear] = e;
	//cout <<"en"<< rear << " " << e << endl;
	return true;
}
//出队列
template<class ElemType>
bool Queue<ElemType>::deQueue(ElemType&e) {
	if (this->QueueEmpty()) {//队列空无法出队列
		cout << "is empty" << endl;
		return false;
	}
	this->front = (this->front + 1) % MaxSize;
	e=this->data[this->front];
	return true;
}
//输出队列
template<class ElemType>
void Queue<ElemType>::DispQueue() {

	int Tfront = (this->front + 1) % MaxSize;
	while (Tfront!=rear%MaxSize) {
		
		cout << data[Tfront] << " ";
		Tfront = (Tfront + 1) % MaxSize;
	}
	cout << data[Tfront] << " ";//最后还要输出最后一个元素,即rear指向的元素

	cout << endl;
}

主函数测试及运行结果:

int main() {
	Queue<int> qu;
	int e;
	qu.enQueue(3);
	qu.enQueue(4);
	qu.enQueue(5);
	qu.enQueue(6);
	qu.DispQueue();

	qu.deQueue(e);
	qu.enQueue(10);
	qu.DispQueue();

	qu.deQueue(e);
	qu.deQueue(e);
	qu.DispQueue();

	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值