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

1. 题目描述

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

2. 思想

(1)栈的特点是先进后出,而队列的特点是先进先出;

(2)因此,入队列的情况和入栈的情况一样stack.push(),用一个栈来模拟就可以了;

(3)而出栈为出栈顶的元素,也即和输入相反(先进后出);然而出队为先进先出,因此借助第2个栈,将第一个站的元素放入第2栈中,再将第2个栈中的元素出栈,也即翻转两次实现了先进先出;

(4)第2个栈为出队列用,当栈2为空时,将栈1中的元素入栈2;当栈2不为空时,也即此时进行出队操作,直接将栈2中元素依次弹出

3. C++完整代码

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <stack>
 5 
 6 
 7 using namespace std;
 8 
 9 class Solution
10 {
11 public:
12     void push(int node) {
13         stack1.push(node);
14     }
15 
16     int pop() {
17         while (stack2.empty())
18         {
19             while (!stack1.empty())
20             {
21                 stack2.push(stack1.top());
22                 stack1.pop();
23             }
24         }
25         int el = stack2.top();
26         stack2.pop();
27         return el;
28     }
29 
30 private:
31     stack<int> stack1;
32     stack<int> stack2;
33 };
34 
35 int main()
36 {
37     Solution *s = new Solution();
38     for (int i = 0; i<8; i++)
39     {
40         s->push(i);
41         if (i >= 4)
42         {
43             int res = s->pop();
44             cout << res << ' ';
45         }
46     }
47     cout << endl;
48     system("pause");
49     return 0;
50 }
View Code

参考资料

https://blog.csdn.net/howe1233/article/details/89504456

原文地址:https://www.cnblogs.com/wxwhnu/p/11400318.html