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

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 1 //一个栈作为队尾(入队),另一个栈作为队头(出队)
 2 //入队时,直接入栈1;出队时,先判断栈2是否empty,为空就将栈1入
 3 //栈2,再出栈
 4 class Solution
 5 {
 6 public:
 7     void push(int node) {
 8         stack1.push(node);
 9     }
10 
11     int pop() {
12         if(stack2.empty()){
13             while(!stack1.empty()){
14                 stack2.push(stack1.top());
15                 stack1.pop();
16             }
17         }
18             int i = stack2.top();
19             stack2.pop();
20             return i;
21         
22     }
23 
24 private:
25     stack<int> stack1;
26     stack<int> stack2;
27 };

 

posted @ 2019-05-11 22:23  unique_ptr  阅读(86)  评论(0编辑  收藏  举报