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

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:栈是后入先出,队列是先入先出;stack1负责插入,stack2负责弹出;因此在插入操作时,就是向stack1中插入;在弹出操作时,需要判断,如果stack2为空就将stack1中全部元素弹出并插入stack2,然后stack2中弹出
 1 #include <iostream>
 2 #include <stack>
 3 using namespace std;
 4 class Solution
 5 {
 6 public:
 7     void push(int node) {
 8         stack1.push(node);
 9     }
10 
11     int pop() {
12         if(stack2.size()<=0)
13         {
14             while(stack1.size()>0)
15             {
16                 int node = stack1.top();
17                 stack1.pop();
18                 stack2.push(node);
19             }
20         }
21         if(stack2.size()==0)
22         {
23             return 0;
24         }
25         int result = stack2.top();
26         cout<<result<<endl;
27         stack2.pop();
28         return result;
29     }
30 
31 private:
32     stack<int> stack1;
33     stack<int> stack2;
34 };
35 int main()
36 {
37     Solution s;
38     s.push(1);
39     s.push(2);
40     s.push(3);
41     s.pop();
42     s.pop();
43     s.pop();
44     return 0;
45 }

运行结果:

 

posted @ 2017-05-04 10:04  qqky  阅读(172)  评论(0编辑  收藏  举报