两个队列实现一个栈

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;

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值