#ifndef QUEUETAG_H
#define QUEUETAG_H
#include
#include
using namespace std;
//顺序表形式的队列,在顺序表的队列定义中一定要注意防止"假溢出"现象的出现
template
class QueueTag{
private:
int front;//队头
int rear;//队尾
int currSize;//当前队列中的元素个数
int maxSize;
bool tag = false;//标记队列是空或满,当tag=true时,为非空
T* str = NULL;//存取数据的空间
public:
QueueTag(int size);
~QueueTag();
void Clear();
void EnQueue(const T value);
void DeQueue();
T ReQueue();
T ReAndDeQueue();
bool isFull();
bool isEmpty();
int Length();
void Print();
};
template
QueueTag::QueueTag(int size)
{
maxSize = size;
str = new T[maxSize];
front = 0;
rear = 0;
}
template
QueueTag::~QueueTag()
{
delete[]str;
}
template
void QueueTag::Clear()
{
//在清空函数中,不仅需要将front=rear,且需要将标记tag=false;
tag = false;
front = rear = 0;
currSize = 0;
}
template
void QueueTag::EnQueue(const T value)
{
if (tag)
{
//tag=true,此时队列为满状态
cout << "队列为满!" << endl;
return;
}
str[rear] = value;
rear = (rear + 1) % maxSize;
currSize++;
if (front == rear)
{
//如果队列状态为满时,则tag=true
tag = true;
}
}
template
void QueueTag::DeQueue()
{
if (!tag&&front==rear)
{
//如果状态为空时,则不进行出队操作
cout << "队列为空!" << endl;
return;
}
front = (front + 1) % maxSize;
currSize--;
if (front == rear&&currSize==0)
{
//当状态为空时,则tag=false;
tag = false;
}
}
template
T QueueTag::ReQueue()
{
if (!tag&&front==rear)
{
cout << "队列为空!" << endl;
return -1;
}
T data = str[front];
return data;
}
template
T QueueTag::ReAndDeQueue()
{
T data = ReQueue();
DeQueue();
return data;
}
template
bool QueueTag::isFull()
{
if (tag)
return false;
return true;
}
template
bool QueueTag::isEmpty()
{
if (!tag)
return true;
return false;
}
template
int QueueTag::Length()
{
return currSize;
}
template
void QueueTag::Print()
{
if (!tag&&front==rear)
return;
int i;
if (front < rear)
{
for (int i = front; i < rear; i++)
{
cout << str[i] << " ";
}
}
else
{
for (int i = front; i < maxSize; i++)
{
cout << str[i] << " ";
}
for (int i = 0; i < rear; i++)
{
cout << str[i] << " ";
}
}
cout << endl;
}
#endif
环形队列,用tag来标记队列的空(0)与满(1)
最新推荐文章于 2023-03-14 19:26:43 发布