TwoStackToQueue 类实现
点击此处浏览C++官方的queue详细内容
主要功能有以下几个
函数 | 功能 |
---|---|
back | 返回对在 queue 后部最近添加的最后一个元素的引用 |
empty | 测试 queue 是否为空 |
front | 返回对 queue 前部的第一个元素的引用 |
pop | 从 queue 前端移除一个元素 |
push | 将元素添加到 queue 的后部 |
size | 返回 queue 中的元素数量 |
基本思路
用一个栈stackPush只接收输入,而用另一个栈stackPop只进行输出和删除操作,那么当stackPush中的元素全部压入stackPop中之后,输出栈的顺序就自然而然变成了先进先出的顺序。其中需要注意一点:当stackPop为空的时候才能够把stackPush中的元素压过去,否则会导致顺序混乱。
代码实现
#include <iostream>
#include <stack>
#include <string>
using namespace std;
template <typename T>
class TwoStackToQueue
{
private:
stack<T> stackPush;
stack<T> stackPop;
T tail;
void move()
{
while (!stackPush.empty())
{
stackPop.push(stackPush.top());
stackPush.pop();
}
}
public:
T back()
{
if (empty())
throw runtime_error("队列为空!");
else
return tail;
}
bool empty()
{
return size() == 0;
}
T front()
{
if (empty())
throw runtime_error("队列为空!");
else
{
if (stackPop.empty())
{
move();
}
return stackPop.top();
}
}
void pop()
{
if (empty())
throw runtime_error("队列为空!");
else
{
if (stackPop.empty())
{
move();
}
stackPop.pop();
}
}
void push(T value)
{
stackPush.push(value);
tail = value;
}
int size()
{
return stackPush.size() + stackPop.size();
}
};
int main()
{
TwoStackToQueue<string> q;
q.push("abc");
q.push("def");
q.push("ghi");
q.push("jkl");
q.push("mno");
q.push("pqr");
int len = q.size();
cout << q.back() << endl;
for (int i = 0; i < len; i++)
{
cout << q.front() << endl;
q.pop();
}
cout << q.empty() << endl;
return 0;
}