剑指offer——07用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 
题解:
  有两个栈,stack1和stack2
  push只在stack1上操作,pop只在stack2上操作
  当stack2不为空时,直接从stack2栈顶弹出
  当stack2为空时,将stack1的数据全部弹出压入stack2中,然后再从stack2中弹出。
 
 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         stack1.push(node);
 6     }
 7 
 8     int pop() {
 9         if (stack2.empty())
10         {
11             while (!stack1.empty())
12             {
13                 stack2.push(stack1.top());
14                 stack1.pop();
15             }            
16         }
17         int res = 0;
18         if (!stack2.empty())
19         {
20             res = stack2.top();
21             stack2.pop();
22         }
23         return res;
24     }
25 
26 private:
27     stack<int> stack1;
28     stack<int> stack2;
29 };
原文地址:https://www.cnblogs.com/zzw1024/p/11652164.html