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();
}