模板实现简易queue
2016-03-29 16:36
344 查看
队列提供了以下操作:
q.empty() //如果队列为空返回true,否则返回false q.size() //返回队列中元素的个数 q.pop() //删除队列首元素的值,但不返回其值 q.front() //返回队列首元素的值,但不删除其值 q.push() //在队尾压入新元素 q.back() //返回队尾元素的值,但不删除其值模拟实现:
/*Queue.cpp*/ #include <iostream> using namespace std; template<class T> struct Node { Node(const T& d) :_data(d) ,_next(NULL) {} T _data; struct Node* _next; }; template<class T> class LinkList { public: LinkList() :_head(NULL) ,_tail(NULL) {} ~LinkList() { if(_head == NULL) { cout<<"List is empty!!"<<endl; return; } Node<T>* cur = _head; while(cur != NULL) { Node<T>* del = cur; cur = cur->_next; delete del; del = NULL; } delete cur; _head = NULL; _tail = NULL; } public: void Display() { Node<T>* cur = _head; while(cur) { cout<<cur->_data<<"-->"; cur = cur->_next; } cout<<"Nvl."<<endl; } void PushBack(const T& d) { Node<T>* NewNode = new Node<T>(d); if(_head == NULL) { _head = NewNode; _tail = _head; } else { _tail->_next = NewNode; _tail = NewNode; } } void PopFront() { if(_head == NULL) { cout<<"Queue is empty!!"<<endl; return; } Node<T>* del =_head; _head = _head->_next; delete del; del = NULL; } int GetListLength() { Node<T>* cur = _head; int count = 0; while(cur) { count++; cur = cur->_next; } return count; } T& GetHeadValue() { if(_head == NULL) { cout<<"Queue is empty!!"<<endl; exit(1); } return _head->_data; } T& GetTailValue() { if(_head == NULL) { cout<<"Queue is empty!!"<<endl; exit(1); } return _tail->_data; } bool JudgeIsEmpty() { if(_head == NULL) { return true; } return false; } private: Node<T>* _head; Node<T>* _tail; }; template<class T, class Container> class Queue { public: void Show() { _con.Display(); } void Push(const T& q) { _con.PushBack(q); } void Pop() { _con.PopFront(); } int Size() { return _con.GetListLength(); } const T& Front() { return _con.GetHeadValue(); } const T& Back() { return _con.GetTailValue(); } bool Empty() { return _con.JudgeIsEmpty(); } private: Container _con; }; int main() { Queue<int,LinkList<int> > q1; q1.Push(1); q1.Push(2); q1.Push(3); q1.Push(4); q1.Push(5); q1.Show(); q1.Pop(); q1.Show(); int size = q1.Size(); cout<<"size = "<<size<<endl; int retTail = q1.Back(); cout<<"retTail = "<<retTail<<endl; int retHead = q1.Front(); cout<<"retHead = "<<retHead<<endl; bool result = q1.Empty(); cout<<"result = "<<result<<endl; system("pause"); return 0; }结果:
相关文章推荐
- Ruby中require、load、include、extend的区别介绍
- vbscript include的办法实现代码第1/2页
- 解析C++编程中的#include和条件编译
- PHP脚本中include文件出错解决方法
- Flex include和import ActionScript代码
- set_include_path在win和linux下的区别
- php include加载文件两种方式效率比较
- How to Auto Include a Javascript File
- 浅谈ASP.NET的include的使用方法
- java/jsp中 中文问题详解
- php相对当前文件include其它文件的方法
- JSP计数器的制作
- php include和require的区别深入解析
- PHP include_path设置技巧分享
- JS 实现完美include载入实现代码
- JS实现完美include加载功能代码
- JSP开发入门(四)--JSP的内部对象
- 实战 J2EE 开发购物网站 二
- php 中include()与require()的对比
- JSP中include指令和include行为的区别