用 class 把 queue 有關 的 data 以及 functions 封藏 (encapsulate)起來! 以下連測試的主程式也寫在一起是偷懶的寫法! tsaiwn@magpie % cat -n myque.cpp 1 // myque.cpp -- queue class by tsaiwn@csie.nctu.edu.tw 2 // g++ myque.cpp ; ./a.out 3 // 以下的 #ifndef 是用來 check 是否為 GNU 的 g++ ? 4 // 若不是則使用舊式的寫法! 例如 Turbo C++ 3.0 只認識舊式的寫法! 5 #ifndef __GNUG__ 6 #include 7 #else 8 #include 9 using namespace std; 10 #endif 11 class MyQueue { 12 enum{ NELEMENT=99 }; // good habit 13 long data[NELEMENT]; 14 int phead, ptail; // phead 指向 queue 的前頭, ptail指向尾巴 15 void initQueue(void){ phead = ptail = 0; } 16 public: 17 MyQueue(void) { initQueue( ); } 18 void enque(long); 19 long deque(void); 20 long front(void) { return data[phead]; } 21 int isempty(void) { return (phead == ptail) ;} 22 int isfull(void) { return ((ptail+1) % NELEMENT) == phead; } 23 ////// ////// 注意 circular queue 的表達方式 24 void push(long x) { enque(x); } 25 long pop(void) { return deque( ); } 26 long top(void) { return front( ); } 27 int empty(void) { return isempty( );} 28 int full(void) { return isfull( );} 29 }; // class MyQueue 30 ////// ////// ////// 31 void MyQueue::enque(long x) { 32 if( isfull() ) { return; } // may want to give some error message? 33 data[ptail] = x; 34 ptail++; 35 ptail %= NELEMENT; /* x %= y; means x = x % y; */ 36 } 37 long MyQueue::deque(void) { 38 if( !isempty() ) { 39 long tmp=data[phead]; 40 phead++; phead %= NELEMENT; 41 return tmp; 42 } // if !isempty 43 } 44 ////// ////// ////// ////// ////// ////// 45 int main( ) { 46 MyQueue xo; 47 xo.enque(53); 48 xo.push(770); 49 xo.push(880); 50 while(!xo.empty( ) ) { 51 cout << xo.top( ) << " "; xo.pop( ); 52 } 53 cout << endl; // new line 54 return 0; 55 } 56 // 此例是把 MyQueue 與 主程式寫在一個檔案, 這是偷懶且不好的方法 57 // 正確方式應該把 MyQueue 獨立, 且應把宣告寫在 .h 檔案, 實作寫 .cpp檔案 58 // 但是若寫為 template class 則通常全部寫在一個 .h 檔案. tsaiwn@magpie % gcc myque.cpp tsaiwn@magpie % ./a.out 53 770 880 tsaiwn@magpie % echo 622