#include <iostream>
#include <fstream>
#include <vector>
using namespace::std;
//队列的基类
template <class E>
class Queue {
public:
Queue() { }; //构造函数
~Queue() { }; //析构函数
virtual bool EnQueue(E x) = 0; //进队列
virtual bool DeQueue(E& x) = 0; //出队列
virtual bool getFront(E& x) = 0; //取队头
virtual bool IsEmpty() const = 0; //判队列空
virtual bool IsFull() const = 0; //判队列满
};
template <class E>
class SeqQueue : public Queue<E> { //循环队列类定义
protected:
int rear, front; //队尾与队头指针
E* elements; //队列存放数组
int maxSize; //队列最大容量
public:
SeqQueue(int sz = 10); //构造函数
SeqQueue(const SeqQueue<E>& a); //复制构造函数
~SeqQueue() {
delete[] elements;
} //析构函数
bool EnQueue(E x); //新元素进队列
bool DeQueue(E& x); //退出队头元素
bool getFront(E& x); //取队头元素值
bool getRear(E& x); //取队尾元素值
void makeEmpty() { front = rear = 0; }//清空队列
bool IsEmpty() const { return front == rear; }//判队空
//判队满
bool IsFull() const { return ((rear + 1) % maxSize == front); }
//返回队列元素个数
int getSize() const { return (rear - front + maxSize) % maxSize; }
//重载=运算符
SeqQueue& operator =(const SeqQueue<E>& a) {
if (this != &a) {
delete[] elements;
front = a.front;
rear = a.rear;
maxSize = a.maxSize;
elements = new E[maxSize]();
for (int i = front; i < rear; i++) {
elements[i] = a.elements[i];
}
}
}
};
//构造函数
template <class E>
SeqQueue<E>::SeqQueue(int sz)
: front(0), rear(0), maxSize(sz) {
elements = new E[maxSize]();
};
//复制构造函数
template <class E>
SeqQueue<E>::SeqQueue(const SeqQueue<E>& a) :
front(a.front), rear(a.rear), maxSize(a.maxSize)
{
elements = new E[maxSize]();
for (int i = front; i < rear; i++) {
elements[i] = a.elements[i];
}
}
//取队头
template <class E>
bool SeqQueue<E>::getFront(E& x) {
//若队列不空则函数返回该队列队头元素的值
if (IsEmpty() == true) return false; //队列空
x = elements[front]; //返回队头元素
return true;
};
//取队尾
template <class E>
bool SeqQueue<E>::getRear(E& x) {
//若队列不空则函数返回该队列队尾元素的值
if (IsEmpty() == true) return false; //队列空
x = elements[rear - 1]; //返回队尾元素
return true;
};
//入队操作
template <class E>
bool SeqQueue<E>::EnQueue(E x)
{
//若队列不满, 则将x插入到该队列队尾, 否则返回
if (IsFull() == true) return false;
elements[rear] = x; //先存入
rear = (rear + 1) % maxSize; //尾指针加一
return true;
};
//出队操作
template <class E>
bool SeqQueue<E>::DeQueue(E& x)
{ //若队列不空则函数退队头元素并返回其值
if (IsEmpty() == true) return false;
x = elements[front]; //先取队头
front = (front + 1) % maxSize; //再队头指针加一
return true;
};
C++循环队列的模板类实现
于 2021-10-19 17:30:30 首次发布