如何使用两个栈模拟队列操作
要求用两个栈来模拟队列,栈A与栈B模拟队列Q,A为插入栈,B为弹出栈,以实现队列Q
假设A和B都为空,可以认为栈A提供入队列的功能,栈B提供出队列的功能
入队列即入栈A;出队列分两种情况考虑:
- 如果栈B不为空,则直接弹出栈B的数据
- 如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据
#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.pop();
}
}
return s2.top();
}