兩個棧模擬隊列

經典問題:

2個棧模擬1個隊列。

棧:先進後出。

隊列:先進先出。

在push的時候,通過另一個棧將序列翻轉一下即可將該棧從棧頂到棧底滿足先進的在更上面的位置。

附代碼如下:

 

  1. #include <stdio.h>  
  2. #include <ctype.h>  
  3. #include <iostream>  
  4.  
  5. using namespace std;  
  6.  
  7. /************************************************************************/ 
  8. /* 兩個棧模擬一個隊列                                                   */ 
  9. /************************************************************************/ 
  10.  
  11. class Queue  
  12. {  
  13. public:  
  14.     Queue()   
  15.     {  
  16.         initStk();  
  17.     }  
  18.  
  19.     //import,using stk2 to converse the serial  
  20.     //O(N)  
  21.     void pushQueue(int value)  
  22.     {  
  23.         while(stk1_top>0) pushStk(popStk(stk1,stk1_top),stk2,stk2_top) ;  
  24.         pushStk(value,stk1,stk1_top);  
  25.         while(stk2_top>0) pushStk(popStk(stk2,stk2_top),stk1,stk1_top) ;  
  26.     }  
  27.  
  28.     //O(1)  
  29.     int popQueue()  
  30.     {  
  31.         return popStk(stk1,stk1_top);  
  32.     }  
  33.  
  34.     int get_length()  
  35.     {  
  36.         return stk1_top ;  
  37.     }  
  38.  
  39.     bool isEmpty()  
  40.     {  
  41.         return stk1_top == 0 ;  
  42.     }  
  43.  
  44. private:  
  45.     int stk1[1024] , stk2[1024] ;  
  46.     int stk1_top , stk2_top ;  
  47.  
  48.     void initStk()  
  49.     {  
  50.         stk1_top = stk2_top = 0 ;  
  51.     }  
  52.  
  53.     //假定不會溢出  
  54.     void pushStk(int value,int stk[],int &stkTop)  
  55.     {  
  56.         stk[stkTop++] = value ;   
  57.     }  
  58.  
  59.     //假定有數據  
  60.     int popStk(int stk[],int &stkTop)  
  61.     {  
  62.         return stk[--stkTop] ;  
  63.     }  
  64.  
  65. };  
  66.  
  67. int main()  
  68. {  
  69.     Queue q ;  
  70.     forint i = 0 ; i < 10 ; i++)  
  71.         q.pushQueue(i) ;  
  72.     while(!q.isEmpty()) printf("%d\n",q.popQueue());  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章