您的位置:首页 > 理论基础 > 数据结构算法

通过设置标志位tag判断队空队满的循环队列

2016-11-04 10:52 330 查看
首先我们定义一个具有基本操作方法的
Queue
类,在这个类中我们设置了一个
bool
型的变量
tag
,通过判断
tag
的值来判断队列是否为空、是否为满。具体是:
rear==front&&!tag
为空,
rear==front&&tag
为满。

queue.h如下:

#ifndef QUEUE_H
#define QUEUE_H

#include<iostream>
using namespace std;

template<class T>
class Queue {
private:
int maxSize;    //存放队列数组的大小
int front;      //表示队头所在位置的下标
int rear;       //表示队尾所在位置的下标
int *queue;     //存放类型为T的队列元素的数组
bool tag;       //0为空,1为不空
public:
Queue(int size);
~Queue() {
delete[] queue;
}
void Clear();       //清空队列
bool EnQueue(const T item);     //item入队,插入队尾
bool DeQueue(T & item);         //返回队头元素,并删除该元素
bool GetFront(T & item);        //返回队头元素但不删除
void disPlay();                 //输出队列
};
template<class T>
Queue<T>::Queue(int size) {
maxSize = size;
tag = 0;
queue = new T[maxSize];
front = rear = 0;
}
template<class T>
void Queue<T>::Clear() {
front = rear;
tag = 0;
}
template<class T>
bool Queue<T>::EnQueue(const T item) {
if (rear==front&&tag) {
cout << "队列已满,溢出!" << endl;
return false;
}
queue[rear] = item;
rear = (rear + 1) % maxSize;
tag = 1;//入队列设为1
return true;
}
template<class T>
bool Queue<T>::DeQueue(T & item) {
if (rear==front&&!tag) {
cout << "队列为空,溢出!" << endl;
return false;
}
item = queue[front];
front = (front + 1) % maxSize;
tag = 0;//出队列设为0
return true;
}
template<class T>
bool Queue<T>::GetFront(T & item) {
if (rear==front&&!tag) {
cout << "队列为空,溢出!" << endl;
return false;
}
item = queue[front];
return true;
}
template<class T>
void Queue<T>::disPlay() {
if (rear==front&&!tag) {
cout << "队列为空!" << endl;
return;
}
if (front == rear&&tag!=0) {
for (int i = 0; i < maxSize; i++) {
cout << queue[i] << " ";
}
}
for (int i = front;; i = (i + 1) % maxSize) {
if (i == rear)
break;
cout << queue[i] << " ";
}
cout << endl;
}
#endif // !QUEUE_H


如下是测试文件source.cpp

#include<iostream>
#include"queue.h"
using namespace std;

int main() {
Queue<int> q(7);
int i = 0;
int item = 0;
q.EnQueue(0);
q.disPlay();
q.EnQueue(1);
q.disPlay();
q.EnQueue(2);
q.disPlay();
q.EnQueue(3);
q.disPlay();
q.EnQueue(4);
q.disPlay();
q.EnQueue(5);
q.disPlay();
q.EnQueue(6);
q.disPlay();
q.EnQueue(7);
q.disPlay();
q.DeQueue(item);
q.EnQueue(6);
q.disPlay();
for (int j = 0; j < 7; j++) {
q.DeQueue(item);
i++;
q.disPlay();
}
return 0;
}


下面看运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 数据结构
相关文章推荐