剑指Offer 用两个栈实现队列

题目描述

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

入队:将元素进栈A

出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;

 如果不为空,栈B直接出栈。

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