c++实现环形队列

环形队列相对于普通队列有一定的好处。
头文件的内容如下:

#include 
class CircleQueue
{
public:
	CircleQueue();
	CircleQueue(int capacity);
	~CircleQueue();
	bool IsEmpty();
	bool IsFull();
	void ClearQueue();
	int Length();
	bool EnQueue(int element);
	bool DeQueue(int &ele);
	void QueueTraverse();
private:
	int *m_pQueue;
	int m_iLen;
	int m_iCapacity;
	int m_iHead;
	int m_iTail;
};

源文件的内容如下:

#include 
#include "CircleQueue.h"
using namespace std;

CircleQueue::CircleQueue()
{
	cout << "CircleQueue::CircleQueue()"<< endl;
}
CircleQueue::CircleQueue(int capacity)
{
	m_iCapacity = capacity;
	m_pQueue = new int[m_iCapacity];
	ClearQueue();
}
CircleQueue::~CircleQueue()
{
	delete []m_pQueue;
	m_pQueue = NULL;
}
bool CircleQueue::IsEmpty()
{
	return m_iLen == 0 ? true : false;

}
bool CircleQueue::IsFull()
{
	return m_iLen == m_iCapacity ? true : false;
}
void CircleQueue::ClearQueue()
{
	m_iLen = 0;
	m_iHead = 0;
	m_iTail = 0;
}
int CircleQueue::Length()
{
	return m_iLen;
}
bool CircleQueue::EnQueue(int element)
{
	if (!IsFull()){
		m_pQueue[m_iTail++] = element;
		m_iTail = m_iTail % m_iCapacity;
		m_iLen++;
		return true;
	}
	return false;
}
bool CircleQueue::DeQueue(int &ele)
{
	if (!IsEmpty()){
		ele = m_pQueue[m_iHead];
		m_iHead++;
		m_iHead = m_iHead % m_iCapacity;
		m_iLen--;
		return true;
	}
	return false;
}
void CircleQueue::QueueTraverse()
{
	if (!IsEmpty()){
		for (int i = m_iHead; i < m_iHead + m_iLen; i++){
			cout << m_pQueue[i%m_iCapacity] << endl;
		}
	}else{
		cout << "Queue is empty!"<< endl;
	}
}

测试程序如下:

#include 
#include "CircleQueue.h"
using namespace std;

int main(void)
{
	CircleQueue q(5);
	q.EnQueue(1);
	q.EnQueue(2);
	q.EnQueue(3);
	q.EnQueue(4);
	q.EnQueue(5);
	q.EnQueue(6);
	q.QueueTraverse();

	int  ele;
	q.DeQueue(ele);
	cout << ele << endl;
	cout << ""<<endl;
	q.QueueTraverse();

	q.ClearQueue();
	q.QueueTraverse();

	q.EnQueue(7);
	q.EnQueue(8);
	q.QueueTraverse();
	system("pause");
	return 0;
}

你可能感兴趣的:(数据结构,环形队列,c++)