关于循环队列,这篇博客介绍的很形象清楚: 点击打开链接,这里给出我自己实现的代码
//
// @file queue.cc
//@author BigDayDreamer(845900796@qq.com)
//
#include <iostream>
using std::cout;
using std::endl;
class Queue
{
public:
Queue(int maxSize);
bool empty();
bool full();
void Enqueue(int num);
void Dequeue();
int getFront();
int getRear();
~Queue();
private:
int _maxSize;
int *_base;
int *_front;
int *_rear;
};
Queue::Queue(int maxSize)
: _maxSize(maxSize)
, _base(new int[_maxSize]())
, _front(_base)
, _rear(_base)
{}
bool Queue::empty()
{
if(_front==_rear)
return 1;
else
return 0;
}
bool Queue::full()
{
if(_front==(_base+(_rear-_base+1)%_maxSize))
return 1;
else
return 0;
}
void Queue::Enqueue(int num)
{
*_rear=num;
_rear=_base+(_rear-_base+1)%_maxSize;
}
void Queue::Dequeue()
{
_front=_base+(_front-_base+1)%_maxSize;
}
int Queue::getFront()
{
return *_front;
}
int Queue::getRear()
{
return *(_rear-1);
}
Queue::~Queue()
{
delete [] _base;
}
int main(void)
{
Queue Q(10);
cout << "Is Queue empty? " << Q.empty() << endl;
cout << "Is Queue full? " << Q.full() << endl;
for(int i=1;i<=100;i++)
{
if(!Q.full())
{
Q.Enqueue(i);
}else
{
cout << "Queue is full" << endl;
break;
}
}
while(!Q.empty())
{
cout << Q.getFront() << " " ;
Q.Dequeue();
}
cout << endl;
cout << "Is Queue empty? " << Q.empty() << endl;
return 0;
}