1、实现原理
设有两个队列A和B,栈的push操作,直接push到A的队尾就行了。栈的pop操作时,将A中的队列依次取出放到B中,取到最后一个时,最后一个不要放到B中,直接删掉,再将B中的值依次放回A中。栈的top操作时,将A中的队列依次取出放到B中,取到最后一个时,将最后一个值记录下来,再将最后一个值放到B中,再将B中的值依次放回到A中。
2、实现代码
#include<iostream>
#include <queue>
using namespace std;
template<class T>
class Mystack
{
public:
Mystack(){}
~Mystack(){}
void Mypush(T t);//入队列
T Mytop();//队头
void Mypop();//出队列
private:
queue<T> A;
queue<T> B;
};
template<class T>
void Mystack<T>::Mypush(T t)
{
A.push(t);
}
template<class T>
T Mystack<T>::Mytop()
{
while (A.size()>1)//队列A中不为空且只剩一个元素
{
B.push(A.front());//A中队头元素压入B队列
A.pop();//A队列元素出队列
}
//循环结束A队列中只有一个元素
T tmp = A.front();//获取该元素
B.push(A.front());//该元素压入队列B
A.pop();
while (B.size() != 0)//把队列B中的元素全部搬到A队列中
{
A.push(B.front());
B.pop();
}
return tmp;//返回A队列中
}
template<class T>
void Mystack<T>::Mypop()
{
while (A.size()>1)
{
B.push(A.front());
A.pop();
}
A.pop();
while (B.size() != 0)
{
A.push(B.front());
B.pop();
}
}
int main()
{
Mystack<int> a;
for (int i = 0; i < 6; i++)
{
a.Mypush(i);
cout << a.Mytop() << " ";
}
cout << endl;
for (int i = 0; i<6; i++)
{
cout << a.Mytop() << " ";
a.Mypop();
}
system("pause");
return 0;
}