C++重写顺序循环队列

事先需要了解:顺序循环队列C语言版

运行环境:VS2017

#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;
typedef int ElemType;		//类型重命名
class CSeqQueue
{
public:
	CSeqQueue(int size);		//构造函数
	~CSeqQueue();			//析构函数
	void Clear()	//清空该队列,可以重新使用
	{
		this->_cursize = 0;		
		this->_front = this->_rear = 0;
	}
	void DestroyQueue()		//摧毁该队列
	{
		this->Clear();
		if (NULL == this->_data)
		{
			return;
		}
		delete[]this->_data;
		this->_data = NULL;
	}
	int GetCursize()	//获取队列当前元素个数
	{
		return this->_cursize;
	}
	int GetCapacity()	//获取队列容量
	{
		return this->_capacity;
	}
	bool QueueIsEmpty()	//队列是否为空
	{
		return this->GetCursize() == 0;
	}
	bool QueueIsFull()	//队列是否为满
	{
		return this->GetCapacity() == this->_cursize;
	}
	ElemType GetFront()	//获得队头元素
	{
		return this->_data[this->_front];
	}
	ElemType GetBack()	//获得队尾元素
	{
		return this->_data[this->_rear];
	}
	bool Push(ElemType kx)	//元素入队
	{
		assert(this->_data != NULL);
		if (this->QueueIsFull())
		{
			return false;	//队列已满,无法插入
		}
		this->_rear = (this->_rear + 1) % this->_capacity;	//队尾指针后移
		this->_data[this->_rear] = kx;
		this->_cursize += 1;
		return true;
	}
	bool Pop(ElemType &kx)	//元素出队
	{
		assert(this->_data != NULL);
		if (this->QueueIsEmpty())
		{
			return false;	//队列已空,再无元素可以出队
		}
		kx = this->GetFront();
		this->_front = (this->_front + 1) % this->_capacity;	//队头指针后移
		this->_cursize -= 1;
		return true;
	}
	void Print()	//打印输出该顺序循环队列
	{
		assert(NULL != this->_data);
		int i = this->_front;
		for (int j = 0; j < this->_cursize; j++)	//控制打印的次数
		{
			cout << this->_data[i] << "    ";
			i = (i + 1) % this->_capacity;   //控制下标 
		}
		cout << endl;
	}
private:
	ElemType * _data;//顺序队列	
	int _front;		//模拟队头指针
	int _rear;		//模拟队尾指针
	int _cursize;	//队列当前元素个数
	int _capacity;	//队列容量
};

CSeqQueue::CSeqQueue(int size)
{
	this->_data = new ElemType[size];
	if (NULL == this->_data)
	{
		exit(1);	//申请空间失败,终止程序
	}
	memset(this->_data, 0, sizeof(ElemType)*this->_capacity);
	this->_capacity = size;
	this->_cursize = 0;
	this->_front = this->_rear = 0;
}

CSeqQueue::~CSeqQueue()
{
	this->DestroyQueue();
}

int main()
{
	ElemType arr[] = { 45,67,43,45,89,98,789,34 };
	int n = sizeof(arr) / sizeof(ElemType);
	CSeqQueue sq(n);
	for (int i = 0; i < n; ++i)
		sq.Push(arr[i]);
	sq.Print();
    return 0;
}

运行环境:VS2017

运行结果

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81280616
今日推荐