【剑指offer 面试题7】用两个栈实现队列

 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 
 5 template <typename T> class SQueue
 6 {
 7 public:
 8     SQueue():cnt(0){};
 9 
10     void push(const T& node);
11     T pop();
12     int getSize();
13 
14 private:
15     stack<T> pushstack;
16     stack<T> popstack;
17 
18     int cnt;
19 };
20 
21 template <typename T> void SQueue<T>::push(const T& node)
22 {
23     pushstack.push(node);
24 
25     cnt++;
26 }
27 
28 template <typename T> T SQueue<T>::pop()
29 {
30     if(popstack.empty())
31     {
32         while(!pushstack.empty())
33         {
34             T tmp = pushstack.top();
35             pushstack.pop();
36             popstack.push(tmp);
37         }
38     }
39 
40     if(popstack.empty())
41     {
42         throw new exception();
43     }
44 
45     T ret = popstack.top();
46     popstack.pop();
47 
48     cnt--;
49 
50     return ret;
51 }
52 
53 template <typename T> int SQueue<T>::getSize()
54 {
55     return cnt;
56 }
57 
58 int main()
59 {
60     SQueue<int> Queue;
61     Queue.push(1);
62     Queue.push(2);
63     Queue.push(3);
64 
65     cout<<"currnet size:"<<Queue.getSize()<<endl;
66 
67     cout<<Queue.pop()<<endl;
68 
69     cout<<"currnet size:"<<Queue.getSize()<<endl;
70 
71     cout<<Queue.pop()<<endl;
72     cout<<Queue.pop()<<endl;
73 }

 

posted @ 2015-06-19 16:21  tjuloading  阅读(134)  评论(0)    收藏  举报