循环队列的C++实现

循环队列的C++实现

#大话数据结构学习
包括了类定义与调用验证
循环队列用两个指针,一个指向队头,一个指向队尾;队尾负责进队,队头负责出队(如同吸管)
缺陷是吸管的长度固定呀!(所以有下一节的链式队列~

#include <bits/stdc++.h>
using namespace std;
/*template <class Datatype>
struct Queue
{
	int front;
	int rear;
	Datatype data;
};*/

template <class Datatype>
class circularQueue
{
	public:
		circularQueue(int max);
		int Length();
		void EnQueue(Datatype e);
		void QuitQueue();
		void print();		
	private:
		/*Queue<Datatype> a[Maxsize];*/
		Datatype *a;
		int front;
		int rear;
		int Maxsize;
};

template <class Datatype>
circularQueue<Datatype>::circularQueue(int max)
{
	Maxsize = max;
	front = 0;
	rear = 0;
	a = new Datatype[Maxsize];
}
template <class Datatype>
int circularQueue<Datatype>::Length()
{
	return (rear-front+Maxsize)%Maxsize;
}
template <class Datatype>
void circularQueue<Datatype>::EnQueue(Datatype e)
{
	if((rear+1)%Maxsize == front)
		throw " full! ";
	a[rear] = e;
	/*if(rear == Maxsize-1&&front !=0)
	{
		rear = 0;
	}
	rear ++;*/
	rear = (rear+1)%Maxsize;
}

template <class Datatype>
void circularQueue<Datatype>::QuitQueue()
{
	if(rear == front)
		throw "Empty!"; 
	//*e = a[front];
	/*front ++;*/
	front = (front + 1)%Maxsize;
	
}
template <class Datatype>
void circularQueue<Datatype>::print()
{
	if(rear == front)
		throw "Empty!"; 
	Datatype *aa;
	aa = a;
	int i;
	/*
	for(i = front;i<rear;i++)
	{
		cout<<"num"<<"["<<i<<"]"<<"="<<aa[i]<<endl;//未考虑循环 
	}*/
	//考虑到循环问题;
	i = front ;
	while(i!=rear)
	{
		cout<<"num"<<"["<<i<<"]"<<"="<<aa[i]<<endl;
		i++;
		i %= Maxsize;
	 } 
	
}
int main()
{
	circularQueue<int> qq(10);
	int data;
	int cnt = 0;
	for(cnt = 0;cnt<9;cnt++){
		qq.EnQueue(cnt*10);
	}
	qq.print();
	printf("length is %d\n",qq.Length());
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
	while(cnt<15)
	{
		qq.QuitQueue();
		cnt++;
	}
	printf("length is %d\n",qq.Length());
	qq.print();
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
	qq.EnQueue(111);
	qq.EnQueue(222);
	qq.EnQueue(333);
	printf("length is %d\n",qq.Length());
	qq.print();
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
	
	qq.QuitQueue();
	qq.print(); 
}
上一篇:【小白学算法】4. 循环队列


下一篇:1057: 有向图的出度计算