您的位置:首页 > 其它

如何使用两个栈模拟队列操作

2014-03-25 19:18 330 查看
思路分析:一个为插入栈,另一个为弹出栈,可以认为插入站提供入队列的功能,弹出栈提供出队列的功能。如果弹出栈不为空,则直接弹出它的数据。如果弹出栈为空,则依次弹出插入栈的数据,放入弹出栈中,再弹出它的数据。

代码如下:

#include "stdafx.h"
#include <iostream>
#include <stack>
using namespace std;
template <typename T>
class QueueByDoubleStack
{
public:
size_t size();
bool empty();
void push(T t);
void pop();
T top();
private:
stack<T> s1;
stack<T> s2;
};
template <typename T>
size_t QueueByDoubleStack<T>::size()
{
return s1.size() + s2.size();
}
template <typename T>
bool QueueByDoubleStack<T>::empty()
{
return s1.empty() && s2.empty();
}
template <typename T>
void QueueByDoubleStack<T>::push(T t)
{
s1.push(t);
}
template <typename T>
void QueueByDoubleStack<T>::pop()
{
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
s2.pop();
}
template <typename T>
T QueueByDoubleStack<T>::top()
{
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.top();
}
}
return s2.top();
}
int main()
{
QueueByDoubleStack<int> q;
for (int i = 0; i < 10; i++)
{
q.push(i);
}
while (!q.empty())
{
cout << q.top() << ' ';
q.pop();
}
cout << endl;
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: