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