说明:
1.这个队列模板逻辑上以循环队列,物理上以元素数组为基础封装
2.队列只能在头出元素,在尾进元素;当头等于尾时认为队列空,当头的下一位置为尾时认为队列满
//--------------------------文件名:queue.h-----------------
#ifndef SUNXYQUEUE_H
#define SUNXYQUEUE_H
const int QDEFAULT=65500;
template<class T>
class SunxyQueue
{
public:
SunxyQueue(int s);
virtual ~SunxyQueue();
T Front();
T Back();
bool In(T entry);
T Out();
int ElemNum();
bool isEmpty();
bool isFull();
virtual void Display();
private:
int head,end,size;
T* array;
};
template<class T>
SunxyQueue<T>::SunxyQueue(int s=QDEFAULT)
{
head=end=0;
if(s<=QDEFAULT&&s>0)
size=s+1;
else
size=QDEFAULT+1;
array=new T[size];
}
template<class T>
SunxyQueue<T>::~SunxyQueue()
{
head=end=0;size=0;
delete[] array;
}
template<class T>
T SunxyQueue<T>::Front()
{
T p;
if(!this->isEmpty())
p=array[end];
return p;
}
template<class T>
T SunxyQueue<T>::Back()
{
T p;
if(!this->isEmpty())
p=(head==0)?array[size-1]:array[head-1];
return p;
}
template<class T>
bool SunxyQueue<T>::In(T entry)
{
bool sign;
if(!this->isFull())
{
array[head]=entry;
head++;
head=(head<size)?head:(head-size);
sign=true;
}
else
sign=false;
return sign;
}
template<class T>
T SunxyQueue<T>::Out()
{
T p;
if(!this->isEmpty())
{
p=array[end];
end++;
end=(end<size)?end:(end-size);
}
return p;
}
template<class T>
int SunxyQueue<T>::ElemNum()
{
int s;
if(!this->isEmpty())
{
if(this->isFull())
s=size-1;
else
s=(head>end)?(head-end):(size-end+head);
}
else
s=0;
return s;
}
template<class T>
bool SunxyQueue<T>::isEmpty()
{
if(head==end)
return true;
else
return false;
}
template<class T>
bool SunxyQueue<T>::isFull()
{
if((((head+1)<size)?(head+1):(head+1-size))==end)
return true;
else
return false;
}
template<class T>
void SunxyQueue<T>::Display()
{
//add codes here
//
}
#endif
//--------------------------queue.h结束---------------------
演示程序:
N个人站成一圈,从一个人开始(令这个人编号为1,顺时针依次将每个人编号)顺时针依次数数,数到M的人出圈,求最后留下的人编号是什么?(如当N=10,M=3时,结果为4)
//---------------------文件名:queuetest.cpp-----------------
#include <iostream>
#include "queue.h"
#include <stdio.h>
#include <time.h>
using namespace std;
//经测试,N=65000,M=365时,运行时间约为4秒
int main(int argc,char* argv[])
{
int m=0,n=0;
while(n<=0)
{
cout<<"Please input the N:";
cin>>n;
}
while(m<=0)
{
cout<<"Please input the M:";
cin>>m;
}
time_t tstart,tend;
tstart=time(NULL);
Queue<int> ring(n);
int i=1;
while(!ring.isFull())
ring.In(i++);
i=1;
while(ring.ElemNum()>1)
{
while(i<m)
{
ring.In(ring.Out());
i++;
}
ring.Out();
i=1;
}
cout<<"The last people is:"<<ring.Back()<<endl;
tend=time(NULL);
//显示运行时间
cout<<endl<<"Elapsed time "<<difftime(tend,tstart)<<" seconds."<<endl;
system("pause");
}
//----------------------queuetest.cpp结束-------------------