C++ 类模板 队列基本操作

来源:互联网 发布:公司内部聊天软件 免费 编辑:程序博客网 时间:2024/05/18 20:48

#include <iostream>#include <string>using namespace std;template<typename QElemType>class QueuePtr{public:QElemType data;QueuePtr* next;};/*结点元素*/ template<typename QElemType>class LinkQueue{private:QueuePtr<QElemType>* front;/*不要拉掉QElemType*/QueuePtr<QElemType>* rear;/*不要拉掉QElemType*/public:// LinkQueue();// ~LinkQueue();bool InitQueue();/*使用队列必须初始化*/bool DestroyQueue();bool ClearQueue();bool QueueEmpty();int QueueLength();bool GetHead_Q(QElemType *e);bool EnQueue(QElemType e);bool DeQueue(QElemType *e);bool QueueTraverse();};template<typename QElemType>bool LinkQueue<QElemType>::InitQueue(){front=rear=new QueuePtr<QElemType>();if(!front)return false;front->next=NULL;return true;} template<typename QElemType>bool LinkQueue<QElemType>::DestroyQueue(){while(front){rear=front->next;delete front;front=rear;}return true;}template<typename QElemType>bool LinkQueue<QElemType>::ClearQueue(){QueuePtr<QElemType>* p=new QueuePtr<QElemType>();QueuePtr<QElemType>* q=new QueuePtr<QElemType>();rear=front;p=front->next;front->next=NULL;while(p){q=p;p=p->next;delete q;}return true; }template<typename QElemType>bool LinkQueue<QElemType>::QueueEmpty(){if(front==rear)return true;elsereturn false;}template<typename QElemType>int LinkQueue<QElemType>::QueueLength(){int i=0;QueuePtr<QElemType>* p=new QueuePtr<QElemType>();p=front;while(rear!=p){i++;p=p->next;}return i; }template<typename QElemType>bool LinkQueue<QElemType>::GetHead_Q(QElemType *e){QueuePtr<QElemType>* p=new QueuePtr<QElemType>();if(front==rear)return false;p=front->next;*e=p->data;return true;}template<typename QElemType>bool LinkQueue<QElemType>::EnQueue(QElemType e){QueuePtr<QElemType>* p=new QueuePtr<QElemType>();if(!p)return false;p->data=e;p->next=NULL;rear->next=p;rear=p;return true;}template<typename QElemType>bool LinkQueue<QElemType>::DeQueue(QElemType *e){QueuePtr<QElemType>* p=new QueuePtr<QElemType>;if(front==rear)return false;p=front->next;*e=p->data;front->next=p->next;if(rear==p)/*当只有一个元素时,对头等于队尾*/rear=front;delete p;return true;}template<typename QElemType>bool LinkQueue<QElemType>::QueueTraverse(){QueuePtr<QElemType>* p=new QueuePtr<QElemType>();p=front->next;while(p){cout<<p->data<<"  ";p=p->next;}cout<<endl;return true;}int main(){LinkQueue<string>Q;LinkQueue<int>L;L.InitQueue();int i=6;L.EnQueue(5);string s;Q.InitQueue();Q.EnQueue("zhao");Q.EnQueue("jin");Q.EnQueue("jia");/*Q.DeQueue(&s);*/Q.GetHead_Q(&s);cout<<s<<endl;/*Q.ClearQueue();*//*Q.DestroyQueue();*/cout<<Q.QueueLength()<<endl;Q.QueueTraverse();cout<<"完毕"<<endl;L.QueueTraverse();system("pause");return 1;}

原创粉丝点击