队列循环实现(C++)
C++队列的循环实现:
View Code
const int MAXQUEUE = 10; template<class T> class ZtkQueue { public: ZtkQueue(); bool empty() const; ErrorCode append(const T &x); ErrorCode serve(); ErrorCode retrieve (T &x)const; bool full() const; int size() const; void clear(); ErrorCode serve_and_retrieve(T &x); private: int count; int rear; int front; T entry[MAXQUEUE]; }; template<class T> ZtkQueue<T>::ZtkQueue():count(0),front(0),rear(MAXQUEUE-1) { } template<class T> ErrorCode ZtkQueue<T>::serve_and_retrieve(T &x) { ErrorCode outcome = success; if(count > 0) { count--; x=entry[front]; front = ((front+1)==MAXQUEUE)?0:front+1; } else outcome = underflow; return outcome; } template<class T> void ZtkQueue<T>::clear() { count=0; rear=MAXQUEUE - 1; front=0; } template<class T> int ZtkQueue<T>::size() const { return count; } template<class T> bool ZtkQueue<T>::full() const { if(count == MAXQUEUE) return true; else return false; } template<class T> ErrorCode ZtkQueue<T>::retrieve(T &x) const { ErrorCode outcome = success; if(!empty()) x = entry[front]; else outcome = underflow; return outcome; } template<class T> ErrorCode ZtkQueue<T>::serve() { ErrorCode outcome = success; if(count>0) { count--; front = ((front+1)==MAXQUEUE)?0:front+1; } else outcome = underflow; return outcome; } template<class T> bool ZtkQueue<T>::empty()const { if(count>0) return false; else return true; } template<class T> ErrorCode ZtkQueue<T>::append(const T &x) { ErrorCode outcome = success; if(count < MAXQUEUE) { count++; rear = ((rear+1)==MAXQUEUE)?0:rear+1; entry[rear]=x; } else outcome = overflow; return outcome; }