通过设置标志位tag判断队空队满的循环队列
2016-11-04 10:52
330 查看
首先我们定义一个具有基本操作方法的
queue.h如下:
如下是测试文件source.cpp
下面看运行结果:
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; }
下面看运行结果:
相关文章推荐
- 循环队列实现(通过设置标志位tag位判断空队满队)
- 要求顺序循环队不损失一个空间,全部能够得到有效利用,试采用设置标志位tag的方法解决“假溢出”问题,实现顺序循环队列算法
- 如何通过循环数组设置button的id?
- android应用面试宝典(下);用自定义组件控制循环组件使用bug还添加标志显示答案标志位;通过包名读取配置文件AndroidManifest.xml
- java通过数组描述队列和循环队列
- 数据结构循环队列,数组实现,循环队列中如果不使用数据项计数字段items,而是通过front和rear计算队列是否为空或满或队列个数,那会很复杂
- 顺序栈S中有2n个元素,从栈顶到栈底的元素依次为a2n、a2n-1、…、a1。试设计一个算法:通过一个循环队列重新排列该栈中的元素,使得从栈顶到栈底的元素先偶数,后奇数
- 解决如何通过循环来使用数据库的值设置jsp的select标签的option值
- 通过共享内存,利用循环队列实现两个进程A,B之间的通信
- 通过循环计时器给页面滚动条设置动画--套路
- 原创:如何实现在Excel通过循环语句设置指定行的格式
- 通过设置标志位让线程停止
- 数据结构:循环队列(一)设置一个标志域后的入队列和出队列的算法
- 如何采用设置标志的方法来区分循环队列的满和空
- c语言写的循环队列
- 通过CMOS设置定时开机
- 怎样通过程序设置使浏览器不出现工具条和minibox,maxbox
- 如何设置ASDL Modem,使内部某台pc可通过域名访问
- 通过一些简单的设置来防止”Ping of Death“攻击
- 通过命令行设置一个系统属性的值