// myque.cpp -- queue class by tsaiwn@csie.nctu.edu.tw // g++ myque.cpp ; ./a.out // 以下的 #ifndef 是用來 check 是否為 GNU 的 g++ ? // 若不是則使用舊式的寫法! 例如 Turbo C++ 3.0 只認識舊式的寫法! #ifndef __GNUG__ #include #else #include using namespace std; #endif class MyQueue { enum{ NELEMENT=99 }; // good habit long data[NELEMENT]; int phead, ptail; // phead 指向 queue 的前頭, ptail指向尾巴 void initQueue(void){ phead = ptail = 0; } public: MyQueue(void) { initQueue( ); } void enque(long); long deque(void); long front(void) { return data[phead]; } int isempty(void) { return (phead == ptail) ;} int isfull(void) { return ((ptail+1) % NELEMENT) == phead; } ////// ////// 注意 circular queue 的表達方式 void push(long x) { enque(x); } long pop(void) { return deque( ); } long top(void) { return front( ); } int empty(void) { return isempty( );} int full(void) { return isfull( );} }; // class MyQueue ////// ////// ////// void MyQueue::enque(long x) { if( isfull() ) { return; } // may want to give some error message? data[ptail] = x; ptail++; ptail %= NELEMENT; /* x %= y; means x = x % y; */ } long MyQueue::deque(void) { if( !isempty() ) { long tmp=data[phead]; phead++; phead %= NELEMENT; return tmp; } // if !isempty } ////// ////// ////// ////// ////// ////// int main( ) { MyQueue xo; xo.enque(53); xo.push(770); xo.push(880); while(!xo.empty( ) ) { cout << xo.top( ) << " "; xo.pop( ); } cout << endl; // new line return 0; } // 此例是把 MyQueue 與 主程式寫在一個檔案, 這是偷懶且不好的方法 // 正確方式應該把 MyQueue 獨立, 且應把宣告寫在 .h 檔案, 實作寫 .cpp檔案 // 但是若寫為 template class 則通常全部寫在一個 .h 檔案.