經典問題:
2個棧模擬1個隊列。
棧:先進後出。
隊列:先進先出。
在push的時候,通過另一個棧將序列翻轉一下即可將該棧從棧頂到棧底滿足先進的在更上面的位置。
附代碼如下:
- #include <stdio.h>
- #include <ctype.h>
- #include <iostream>
- using namespace std;
- /************************************************************************/
- /* 兩個棧模擬一個隊列 */
- /************************************************************************/
- class Queue
- {
- public:
- Queue()
- {
- initStk();
- }
- //import,using stk2 to converse the serial
- //O(N)
- void pushQueue(int value)
- {
- while(stk1_top>0) pushStk(popStk(stk1,stk1_top),stk2,stk2_top) ;
- pushStk(value,stk1,stk1_top);
- while(stk2_top>0) pushStk(popStk(stk2,stk2_top),stk1,stk1_top) ;
- }
- //O(1)
- int popQueue()
- {
- return popStk(stk1,stk1_top);
- }
- int get_length()
- {
- return stk1_top ;
- }
- bool isEmpty()
- {
- return stk1_top == 0 ;
- }
- private:
- int stk1[1024] , stk2[1024] ;
- int stk1_top , stk2_top ;
- void initStk()
- {
- stk1_top = stk2_top = 0 ;
- }
- //假定不會溢出
- void pushStk(int value,int stk[],int &stkTop)
- {
- stk[stkTop++] = value ;
- }
- //假定有數據
- int popStk(int stk[],int &stkTop)
- {
- return stk[--stkTop] ;
- }
- };
- int main()
- {
- Queue q ;
- for( int i = 0 ; i < 10 ; i++)
- q.pushQueue(i) ;
- while(!q.isEmpty()) printf("%d\n",q.popQueue());
- }