#include <queue>
template <typename T>
class CStack
{
public:
void AddToTail(const T&);
T deleteHead();
private:
std::queue<T> queue1;
std::queue<T> queue2;
};
template <typename T>
void CStack<T>::AddToTail(const T& value)
{
queue1.push(value);
}
template <typename T>
T CStack<T>::deleteHead()
{
int flat = 0;
if (!queue1.empty())
{
while (queue1.size() > 1)
{
T& data = queue1.back();
queue2.push(data);
queue1.pop();
}
flat = 1;
}
else
{
while (queue2.size() > 1)
{
T& data = queue2.back();
queue1.push(data);
queue2.pop();
}
flat = 2;
}
T result;
if (flat == 1)
{
result = queue1.back();
queue1.pop();
}
else if (flat == 2)
{
result = queue2.back();
queue2.pop();
}
else
{
throw new exception("stack is empty");
}
return result;
}
用两个队列实现栈
最新推荐文章于 2024-08-19 13:32:52 发布