//-----------------------------------------------CirularQueue.h------------------------------------------------
template <class T>
class cirularQueue
{
private:
int maxSize;
int front;
int rear;
T *data;
public:
cirularQueue(int maxLength)
{
maxSize=maxLength;
cout<<"循环队列的最大长度为:"<<maxSize<<endl;
front=rear=0;
data=new T[maxLength];
}
~cirularQueue()
{
front=rear=0;
delete []data;
cout<<"调用析构函数!"<<endl;
}
bool isFull()
{
return (rear+1)%maxSize==front;
}
bool isEmpty()
{
return front==rear;
}
bool push(T info)
{
if(isFull())
{
cout<<"错误!队列已满!"<<endl;
return false;
}
else
{
data[rear]=info;
rear=(rear+1)%maxSize;
return true;
}
}
bool pop(T &info)
{
if(isEmpty())
{
cout<<"错误!队列为空!"<<endl;
return false;
}
else
{
info=data[front];
front=(front+1)%maxSize;
return true;
}
}
bool getHead(T &info)
{
if(isEmpty())
{
cout<<"错误!队列为空!"<<endl;
return false;
}
else
{
info=data[front];
return true;
}
}
void print()
{
if(isEmpty())
{
cout<<"队列为空,没有数据可以输出!"<<endl;
}
else
{
int i=front;
while(i!=rear)
{
cout<<data[i]<<" ";
i=(i+1)%maxSize;
}
cout<<endl;
}
}
};
//-------------------------------------------------CirularQueue.cpp-----------------------------------------------------
// cirularQueue.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "cirularQueue.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//cout<<"请输入需要初始化队列的最大长度:";
const int maxLength=5;
//cin>>maxLength;
cirularQueue<char> myQueue(maxLength);
cout<<"请输入需要实际需要初始化的数据个数(实际可输入数据的最大数目为队列最大长度减1):";
int n;
cin>>n;
char info;
for(int i=0;i<n;i++)
{
cout<<"请输入第"<<i+1<<"个数据:";
cin>>info;
myQueue.push(info);
}
myQueue.print();
cout<<endl;
cout<<"请输入需要入队的数据值:";
cin>>info;
if(myQueue.push(info))
{
myQueue.print();
}
cout<<endl;
cout<<"队首出队"<<endl;
if(myQueue.pop(info))
{
cout<<"出队的数据的值为:"<<info<<endl;
myQueue.print();
}
cout<<endl;
cout<<"返回队首"<<endl;
if(myQueue.getHead(info))
{
cout<<"队首的数据值为:"<<info<<endl;
myQueue.print();
}
cout<<endl;
return 0;
}