转载:http://blog.csdn.net/stpeace/article/details/46765343
利用两个栈来实现一个队列, 这个问题很常见。 最关键的是要有好的思路, 至于实现, 那是很简单的事情了。 在本文中, 也想说说自己的思路, 但是, 我觉得用代码来表述思路更符合我的习惯, 也是我的菜, 所以, 仅仅给出代码。 如有需要, 大家可以根据代码来理解思路。
OK, 没有必要废话了, 直接上代码:
[cpp] view plaincopy
- #include <iostream>
- #include <stack>
- using namespace std;
- // 用两个stack实现一个queue, 以int类型为例吧
- class MyQueque
- {
- private:
- stack<int> s1; // s1负责入队
- stack<int> s2; // s2负责出队
- public:
- // 入队
- void push(int x)
- {
- s1.push(x);
- }
- // 出队
- void pop()
- {
- if(!s2.empty())
- {
- s2.pop();
- }
- else
- {
- while(!s1.empty())
- {
- int tmp = s1.top();
- s1.pop();
- s2.push(tmp);
- }
- s2.pop();
- }
- }
- // 取头
- int front()
- {
- if(!s2.empty())
- {
- return s2.top();
- }
- while(!s1.empty())
- {
- int tmp = s1.top();
- s1.pop();
- s2.push(tmp);
- }
- return s2.top();
- }
- // 取尾
- int back()
- {
- if(!s1.empty())
- {
- return s1.top();
- }
- while(!s2.empty())
- {
- int tmp = s2.top();
- s2.pop();
- s1.push(tmp);
- }
- return s1.top();
- }
- // 求大小
- int size()
- {
- return s1.size() + s2.size();
- }
- // 判断是否为空
- bool empty()
- {
- if(s1.empty() && s2.empty())
- {
- return true;
- }
- return false;
- }
- };
- int main()
- {
- {
- MyQueque que;
- que.push(1);
- que.push(2);
- que.push(3);
- que.push(4);
- que.push(5);
- while(!que.empty())
- {
- cout << que.front() << endl;
- que.pop();
- }
- cout << "-------------------" << endl;
- }
- {
- MyQueque que;
- que.push(1);
- que.push(2);
- que.push(3);
- que.push(4);
- que.push(5);
- while(!que.empty())
- {
- cout << que.size() << endl;
- que.pop();
- }
- cout << "-------------------" << endl;
- }
- {
- MyQueque que;
- que.push(1);
- que.push(2);
- que.push(3);
- que.pop();
- que.pop();
- que.push(4);
- que.push(5);
- while(!que.empty())
- {
- cout << que.front() << endl;
- que.pop();
- }
- cout << "-------------------" << endl;
- }
- return 0;
- }
1
2
3
4
5
-------------------
5
4
3
2
1
-------------------
3
4
5
-------------------