剑指Offer——用两个栈实现队列

题目描述:

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


分析:

 

代码:

 1 class Solution {
 2 public:
 3     void push(int node) {
 4         stack1.push(node);
 5     }
 6 
 7     int pop() {
 8         if(stack2.empty()) {
 9             while(!stack1.empty()) {
10                 stack2.push(stack1.top());
11                 stack1.pop();
12             }
13         }
14         int t = stack2.top();
15         stack2.pop();
16         return t;
17     }
18 
19 private:
20     stack<int> stack1;
21     stack<int> stack2;
22 };

 

posted @ 2017-10-27 11:32  叶建成  阅读(165)  评论(0编辑  收藏  举报