链式队列
2012-04-08 23:03 Rollen Holt 阅读(758) 评论(0) 编辑 收藏 举报QueueNode.h
template<typename Type> class LinkQueue; template<typename Type> class QueueNode{ private: friend class LinkQueue<Type>; QueueNode(const Type item,QueueNode<Type> *next=NULL) :m_data(item),m_pnext(next){} private: Type m_data; QueueNode<Type> *m_pnext; };
LinkQueue.h
#include "QueueNode.h" template<typename Type> class LinkQueue{ public: LinkQueue():m_prear(NULL),m_pfront(NULL){} ~LinkQueue(){ MakeEmpty(); } void Append(const Type item); //insert data Type Delete(); //delete data Type GetFront(); //get data void MakeEmpty(); //make the queue empty void Print(); //print the queue bool IsEmpty() const{ return m_pfront==NULL; } private: QueueNode<Type> *m_prear,*m_pfront; }; template<typename Type> void LinkQueue<Type>::MakeEmpty(){ QueueNode<Type> *pdel; while(m_pfront){ pdel=m_pfront; m_pfront=m_pfront->m_pnext; delete pdel; } } template<typename Type> void LinkQueue<Type>::Append(const Type item){ if(m_pfront==NULL){ m_pfront=m_prear=new QueueNode<Type>(item); } else{ m_prear=m_prear->m_pnext=new QueueNode<Type>(item); } } template<typename Type> Type LinkQueue<Type>::Delete(){ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } QueueNode<Type> *pdel=m_pfront; Type temp=m_pfront->m_data; m_pfront=m_pfront->m_pnext; delete pdel; return temp; } template<typename Type> Type LinkQueue<Type>::GetFront(){ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } return m_pfront->m_data; } template<typename Type> void LinkQueue<Type>::Print(){ QueueNode<Type> *pmove=m_pfront; cout<<"front"; while(pmove){ cout<<"--->"<<pmove->m_data; pmove=pmove->m_pnext; } cout<<"--->rear"<<endl<<endl<<endl; }
Test.cpp
#include <iostream> using namespace std; #include "LinkQueue.h" int main(){ LinkQueue<int> queue; int init[10]={1,3,6,8,9,2,0,5,4,7}; for(int i=0;i<10;i++){ queue.Append(init[i]); } queue.Print(); queue.Delete(); queue.Print(); cout<<queue.GetFront()<<endl; queue.Print(); queue.MakeEmpty(); queue.Print(); queue.Delete(); return 0; }
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================