1. 原理
队列是带先入先出FIFO特性的数据结构。为了充分利用队列,顺序队列常常做成一个逻辑上的循环队列。
注意:空队时rear等于front,满队时front = (rear+1) mod N,必须空一个位置。
2. 设计
2.1 属性
- m_size 队列大小
- m_front, 队头
- m_rear, 队尾
- m_data, 数据存存储区
2.2 方法
- isEmpty()
- isFull()
- push()
- pop()
3. 原始实现
3.1 类实现
#include <iostream>
using namespace std;
template <class T>
class CycleQueue
{
private:
unsigned int m_size;
int m_front;
int m_rear;
T* m_data;
public:
CycleQueue(unsigned size)
:m_size(size),
m_front(0),
m_rear(0)
{
m_data = new T[size];
}
~CycleQueue()
{
delete [] m_data;
}
bool isEmpty()
{
return m_front == m_rear;
}
bool isFull()
{
return m_front == (m_rear + 1)%m_size;
}
void push(T ele) throw(bad_exception)
{
if(isFull())
{
throw bad_exception();
}
m_data[m_rear] = ele;
m_rear = (m_rear + 1)%m_size;
}
T pop() throw(bad_exception)
{
if(isEmpty())
{
throw bad_exception();
}
T tmp = m_data[m_front];
m_front = (m_front + 1)%m_size;
return tmp;
}
};
3.2 测试程序
int main()
{
CycleQueue<int> q(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
for (int i = 0; i < 4 ; i++)
cout << q.pop() << endl;
q.push(5);
q.push(5);
q.push(5);
cout << q.pop() << endl;
cout << q.pop() << endl;
cout << q.pop() << endl;
return 0;
}
4. 加锁优化实现
4.1 模板类实现
#include <iostream>
#include <QMutex>
using namespace std;
template <class T>
class CycleQueue
{
private:
QMutex m_mutex;
unsigned int m_size;
unsigned int m_front;
unsigned int m_rear;
T* m_data;
public:
CycleQueue(unsigned size)
:m_size(size),
m_front(0),
m_rear(0)
{
m_data = new T[size];
}
~CycleQueue()
{
delete [] m_data;
}
bool isEmpty()
{
return m_front == m_rear;
}
bool isFull()
{
return m_front == (m_rear + 1)%m_size;
}
bool push(T element)
{
bool bRet = false;
m_mutex.lock();
if(!isFull())
{
m_data[m_rear] = element;
m_rear = (m_rear + 1) % m_size;
bRet = true;
}
m_mutex.unlock();
return bRet;
}
bool pop(T& element)
{
bool bRet = false;
m_mutex.lock();
if(!isEmpty())
{
element = m_data[m_front];
m_front = (m_front + 1) % m_size;
bRet = true;
}
m_mutex.unlock();
return bRet;
}
};
4.2 环形队列测试程序
const int MAXQUEUE = 6;
int main()
{
int ntmp;
CycleQueue<int> q(MAXQUEUE + 1);
cout << "Queue with max :" << MAXQUEUE << " Space is created!"<< endl;
for (int i = 0; i < 8 ; i++)
{
bool bres = q.push(i);
if(bres)
cout << "enqueue:" << i << endl;
else {
cout << "queue is full!" << endl;
}
}
for (int i = 0; i < 4 ; i++)
{
bool bres = q.pop(ntmp);
if(bres)
cout << "dequeue:" << ntmp << endl;
else {
cout << "queue is empty!" << endl;
}
}
for (int i = 0; i < 8 ; i++)
{
bool bres = q.push(i);
if(bres)
cout << "enqueue:" << i << endl;
else {
cout << "queue is full!" << endl;
}
}
for (int i = 0; i < 10 ; i++)
{
bool bres = q.pop(ntmp);
if(bres)
cout << "dequeue:" << ntmp << endl;
else {
cout << "queue is empty!" << endl;
}
}
return 0;
}
4.3 运行结果