针对顺序队列中的入队操作:if 队列没满,但是队尾到达数组末尾了,队列"满"了,其实没有满,数据需要整体移至数组头部,才可以继续入队。
为解决该问题,避免数据的挪移,有了循环顺序队列
循环顺序队列的思路:
- 当队列未满,队尾到达数组末尾了,让 tail 的数组下标跳至0;
- 判断队列是否满,可以用队列长度==容量,或者用求模运算(少用一个数组空间,(tail+1)%capacity = head 则队列满了)
完成代码见:https://github.com/hitskyer/course/tree/master/dataAlgorithm/chenmingming/queue
1. 主要修改
入队函数修改
bool circularQueue<T>::enqueue(const T &data)
{
if(full())
return false;
else
{
if(empty())
{
m_pHead = m_pTail = 0;
arrQ[0] = data;
m_QueueLen++;
}
else if(m_pTail < m_capacity-1)
{
arrQ[++m_pTail] = data;
m_QueueLen++;
}
else //队列没满,但是队尾到达数组末尾了,让tail变成-1
{
if(m_pTail + 1 == m_capacity)
m_pTail = -1;
arrQ[++m_pTail] = data;
m_QueueLen++;
}
return true;
}
}
打印函数修改
void circularQueue<T>::print() const
{
if(empty())
cout << "empty queue!" << endl;
cout << "circularQueue from head to tail as follow:" << endl;
int j = m_pHead;
for(UINT i = 0; i < m_QueueLen; )
{
if(j == m_capacity) //打印时注意下标循环跳转
j = 0;
cout << "No." << ++i << " elem is " << arrQ[j++] << endl;
}
cout << "--------------print end----------------" << endl;
}