类定义:
#include<iostream>
#define MaxSize 4
using namespace std;
template<class ElemType>
class Queue{
private:
ElemType *data;
int front, rear;
public:
Queue();
~Queue();
bool QueueEmpty();
bool QueueFull();
bool enQueue(ElemType e);
bool deQueue(ElemType&e);
void DispQueue();
};
类中各函数:
template<class ElemType>
Queue<ElemType>::Queue() {
this->data = new ElemType[MaxSize];
front = 0;
rear = 0;
}
template<class ElemType>
Queue<ElemType>::~Queue() {
if (this->data == NULL) {
return;
}
delete this->data;
}template<class ElemType>
bool Queue<ElemType>::QueueEmpty() {
return this->front == this->rear;
}
template<class ElemType>
bool Queue<ElemType>::QueueFull() {
return (this->rear+1)%MaxSize==this->front;
}
template<class ElemType>
bool Queue<ElemType>::enQueue(ElemType e) {
if (this->QueueFull()) {
cout << "is Full" << endl;
return false;
}
this->rear = (this->rear + 1) % MaxSize;
this->data[this->rear] = e;
return true;
}
template<class ElemType>
bool Queue<ElemType>::deQueue(ElemType&e) {
if (this->QueueEmpty()) {
cout << "is empty" << endl;
return false;
}
this->front = (this->front + 1) % MaxSize;
e=this->data[this->front];
return true;
}
template<class ElemType>
void Queue<ElemType>::DispQueue() {
int Tfront = (this->front + 1) % MaxSize;
while (Tfront!=rear%MaxSize) {
cout << data[Tfront] << " ";
Tfront = (Tfront + 1) % MaxSize;
}
cout << data[Tfront] << " ";
cout << endl;
}
主函数测试及运行结果:
int main() {
Queue<int> qu;
int e;
qu.enQueue(3);
qu.enQueue(4);
qu.enQueue(5);
qu.enQueue(6);
qu.DispQueue();
qu.deQueue(e);
qu.enQueue(10);
qu.DispQueue();
qu.deQueue(e);
qu.deQueue(e);
qu.DispQueue();
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9dc12f0753c77b0f9d6b449b14d64197.png)