循环队列是一种基于数组实现的队列数据结构,其特点是队尾和队头通过模运算相连,形成一个环形结构。这种设计可以有效地利用数组空间,避免因出队操作导致队列空间的浪费。
循环队列通常有两个指针,一个指向队头(front),另一个指向队尾(rear)。初始时,这两个指针都指向队列的起始位置。当有元素入队时,队尾指针移动到下一个位置;当有元素出队时,队头指针也移动到下一个位置。如果指针达到数组的末尾,它将会绕回到数组的开头,形成一个循环。
循环队列的主要优势在于可以在数组中实现高效的循环操作,而不需要频繁地搬移数据。这对于需要频繁执行入队和出队操作的场景非常有用,比如缓冲区管理、任务调度等。
基本的循环队列操作包括:
入队(Enqueue): 将元素添加到队尾,同时移动队尾指针。
出队(Dequeue): 移除队头元素,同时移动队头指针。
判空(isEmpty): 判断队列是否为空。
判满(isFull): 判断队列是否已满。
_public.h#ifndef __PUBLIC_HH [50/33042]
#define __PUBLIC_HH
#include
#include
#include
using namespace std;
template<class TT, int MaxLength>
class squeue
{
private:
bool m_inited;
int m_length;
TT m_data[MaxLength];
int m_head;
int m_tail;
// 禁用拷贝构造函数以及赋值运符
squeue(const squeue& ss) = delete;
squeue& operator=(const squeue& ss) = delete;
public:
squeue() {init();}
void init()
{
if (m_inited)
return ;
m_inited = true;
m_length = 0;
// 头尾指针分别处在数组两侧
m_head = 0;
m_tail = MaxLength - 1;
memset(m_data, 0, sizeof(m_data));
}
bool push(const TT& value)
{
if (is_full())
{
cout << "squeue is full..." << endl;
return false;
}
// 每次向尾部添加数据时,先将尾结点向后移动一位
m_tail = (m_tail + 1) % MaxLength;
m_data[m_tail] = value;
// 总长度++
m_length ++ ;
return true;
}
bool is_full()
{
if (m_length == MaxLength) return true;
return false;
}
bool is_empty()
{
if (!m_length) return true;
return false;
}
TT& front()
{
return m_data[m_head];
}
bool pop()
{
if (!is_empty())
{
// 取数据时同样也是先将头指针向后移动,再pop数据
m_head = (m_head + 1) % MaxLength;
m_length -- ;
return true;
}
return false;
}
int size()
{
return m_length;
}
};
#endif
_public.cpp#include <_public.h>
int main()
{
squeue<int, 3> q;
q.push(12);
q.push(14);
q.push(6);
q.push(2);
return 0;
}