2.使用两个栈实现一个队列。
思想:栈是先进后出的数据结构,队列是先进先出的数据结构,要用两个栈实现一个队列,就必须让两个栈实现元素的先进先出。入栈时,让需要入栈的元素全都进入S1栈中,出栈时,再把S1中的元素依次出栈,入S2栈,再把S2的栈顶元素弹出。
如下图所示:
当然,这个过程过于繁琐,有可以优化的方法
如下图所示:
代码实现:
//两个栈实现一个队列
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
template<class T>
class Queue
{
public:
/*Queue()
:spush(NULL)
,spop(NULL)
{}*/
void Push(const T& x)
{
spush.push(x);
}
void Pop()
{
if (!spop.empty())
{
spop.pop();
}
else
{
while (spush.size() > 1)
{
T tmp = spush.top();
spop.push(tmp);
spush.pop();
}
spush.pop();
while (!spop.empty())
{
T tmp = spop.top();
spush.push(tmp);
spop.pop();
}
}
}
size_t Size()
{
return spush.size();
}
bool Empty()
{
return spush.empty();
}
protected:
stack<T> spush;
stack<T> spop;
};
Test.c
void Test()
{
Queue<int> q1;
q1.Push(0);
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Push(5);
q1.Pop();
q1.Pop();
q1.Pop();
}
3.使用两个队列实现一个栈
思想:与两个栈实现一个队列相似,使用两个队列实现先进后出的特性,出队列时,先将q1中的元素依次出队再入队到q2队列,然后再将q2队列的队首元素弹出,最后,把q2队列的元素再依次出队入队到q1队列
如下图所示:
然后再把q2队列中的元素倒回q1队列
优化:将q1中除了队尾元素全部倒入q2队列中,直接弹出q1中仅剩的元素,就可以少倒一次元素
代码实现:
//两个队列实现一个栈
#include <iostream>
#include <queue>
using namespace std;
template<class T>
class Stack
{
public:
void Push(const T& x)
{
qpush.push(x);
}
void Pop()
{
if (!qpush.empty())
{
while (qpush.size() > 1)
{
T tmp = qpush.front();
qpop.push(tmp);
qpush.pop();
}
qpush.pop();
while (!qpop.empty())
{
T tmp = qpop.front();
qpush.push(tmp);
qpop.pop();
}
}
else
{
qpop.pop();
}
}
protected:
queue<T> qpush;
queue<T> qpop;
};
Test.c
void Test()
{
Stack<int> s1;
s1.Push(0);
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Push(5);
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
}