剑指offer---用两个栈实现队列

题目:用两个栈实现队列

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

 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         
 6     }
 7 
 8     int pop() {
 9         
10     }
11 
12 private:
13     stack<int> stack1;
14     stack<int> stack2;
15 };

解题代码:

 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             while(!stack1.empty()){
11                 stack2.push(stack1.top());
12                 stack1.pop();
13             }
14         }
15         int res = stack2.top();
16         stack2.pop();
17         return res;
18     }
19 
20 private:
21     stack<int> stack1;
22     stack<int> stack2;
23 };

 

posted on 2018-10-24 10:56  wangzhch  阅读(113)  评论(0编辑  收藏  举报

导航