这里使用C++实现
template <class T>
class CycleQueue
{
private:
unsigned int m_size;
int m_front;
int m_rear;
T* m_data;
public:
CycleQueue(unsigned size) :
m_rear(0), m_front(0) {
m_size = size + 1;
m_data = new T[size + 1];
// m_size(size + 1),
}
~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 res = m_data[m_front];
m_front = (m_front + 1) % m_size;
return res;
}
};
思想:利用取余的方法来实现头指针和尾指针的移动;利用头尾位置来判断队列的空和满
对比:python写这个类的话,全程会有self.m_data, self.m_front,写起来很冗长;这里C++写起来少些“self”,看着也舒服