这篇写的是环形队列,上一篇顺序队列中也提到了,环形队列设计的初衷就是为了解决假溢出问题,那他是如何成为环形的呢?换句话说,指针是怎么从数组的后面回到前面来的呢?取余,环形队列的核心就是取余。
back=(back+1)%maxSize;
front=(front+1)%maxSize;
大致上就是这两个操作,总之,问就是取余。
实现代码如下所示:
(PS:main函数里的是我自己的测试代码,我能确定不会发生假溢出,有没有其他bug我就没有测试啦 :P )
#include<iostream>
#include<vector>
using namespace std;
class circularQueue
{
private:
int maxSize;
int size;
int front;
int back;
vector<int> q;
public:
circularQueue(int max);
~circularQueue();
bool enQueue(int value);
bool deQueue();
int getFront();
bool isEmpty();
bool isFull();
};
circularQueue::circularQueue(int max=100)
{
maxSize = max;
size = 0;
front = 0;
back = 0;
q = vector<int>(max);
}
circularQueue::~circularQueue()
{
q.clear();
}
bool circularQueue::enQueue(int value)
{
if ((back + 1)%maxSize == front) //队列为满
{
return false;
}
else
{
q[back] = value;
back = (back + 1) % maxSize;
size++;
return true;
}
}
bool circularQueue::deQueue()
{
if (front == back) //为空
{
return false;
}
else
{
front = (front + 1) % maxSize;
size--;
return true;
}
}
int circularQueue::getFront()
{
if (front == back)
{
return 0;
}
else
{
return q[front];
}
}
bool circularQueue::isEmpty()
{
if (front == back)
{
return true;
}
else
{
return false;
}
}
bool circularQueue::isFull()
{
if ((back + 1) % maxSize == front)
{
return true;
}
else
{
return false;
}
}
int main()
{
circularQueue *cq = new circularQueue();
cout << cq->isEmpty() << endl;
for (int i = 0; i < 99; i++)
{
cq->enQueue(i);
}
cout << cq->isFull() << endl;
for (int i = 0; i < 49; i++)
{
cq->deQueue();
cout << cq->getFront() << endl;
}
for (int i= 0; i < 49; i++)
{
cq->enQueue(i);
}
for (int i = 0; i < 49; i++)
{
cq->deQueue();
cout << cq->getFront() << endl;
}
for (int i = 0; i < 49; i++)
{
cq->enQueue(i);
}
for (int i = 0; i < 49; i++)
{
cq->deQueue();
cout << cq->getFront() << endl;
}
system("pause");
return 0;
}