C++ 泛型 编写的 数据结构 队列
平时编程里经常需要用到数据结构,比如 栈和队列 等, 为了避免每次用到都需要重新编写的麻烦现将 C++ 编写的 数据结构 队列 记录下来,以备后用。
将 数据结构 队列 用头文件的形式写成,方便调用。
#ifndef QUEUE_CLASS #define QUEUE_CLASS #include<iostream> #include<cstdlib> using namespace std; const int MaxQSize=50; template <class T> class Queue { private: int front, rear, count; T qlist[MaxQSize]; public: Queue(void); void QInsert(const T &item); T QDelete(void); void ClearQueue(void); T QFront(void) const; int QLength(void) const; int QEmpty(void) const; int QFull(void) const; }; //默认构造函数 template <class T> Queue<T>::Queue(void):front(0), rear(0), count(0) {} template <class T> void Queue<T>::QInsert(const T &item) { if(count==MaxQSize) { cerr<<"Queue overflow!"<<endl; exit(1); } count++; qlist[rear]=item; rear=(rear+1)%MaxQSize; } template <class T> T Queue<T>::QDelete(void) { T temp; if(count==0) { cerr<<"Deleting from an empty queue!"<<endl; exit(1); } count--; temp=qlist[front]; front=(front+1)%MaxQSize; return temp; } template <class T> T Queue<T>::QFront(void) const { return qlist[front]; } template <class T> int Queue<T>::QLength(void) const { return count; } template <class T> int Queue<T>::QEmpty(void) const { return count==0; } template <class T> int Queue<T>::QFull(void) const { return count==MaxQSize; } template <class T> void Queue<T>::ClearQueue(void) { front=0; rear=0; count=0; } #endif
具体的调用形式:
运行结果:
本博客是博主个人学习时的一些记录,不保证是为原创,个别文章加入了转载的源地址,还有个别文章是汇总网上多份资料所成,在这之中也必有疏漏未加标注处,如有侵权请与博主联系。
如果未特殊标注则为原创,遵循 CC 4.0 BY-SA 版权协议。
posted on 2017-01-26 09:08 Angry_Panda 阅读(720) 评论(0) 编辑 收藏 举报