用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

好像第二种更好一点,毕竟push操作的频率高于pop。

 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         if(stack1.empty())
 6             stack1.push(node);
 7         else{
 8             while(!stack1.empty()){
 9                 stack2.push(stack1.top());
10                 stack1.pop();
11             }
12             stack1.push(node);
13             while(!stack2.empty()){
14                 stack1.push(stack2.top());
15                 stack2.pop();
16             }
17         }
18     }
19 
20     int pop() {
21         int t=stack1.top();
22         stack1.pop();
23         return t;
24     }
25 
26 private:
27     stack<int> stack1;
28     stack<int> stack2;
29 };
 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         stack1.push(node);
 6     }
 7  
 8     int pop() {
 9         int t;
10         while(stack1.size()>1)
11         {
12             stack2.push(stack1.top());
13             stack1.pop();
14         }
15         t = stack1.top();
16         stack1.pop();
17         while(stack2.size()>0)
18         {
19             stack1.push(stack2.top());
20             stack2.pop();
21         }
22         return t;
23     }
24  
25 private:
26     stack<int> stack1;
27     stack<int> stack2;
28 };
原文地址:https://www.cnblogs.com/zl1991/p/4757967.html