两个队列实现一个栈——栈和队列面试题(3)

题目要求:用两个队列实现一个栈,实现栈的内部函数


“test.cpp”

<strong><span style="font-size:18px;">#include<iostream>
using namespace std;
#include<queue>

template<class T>
class TwoQueueFromStack
{
public:
	TwoQueueFromStack(){}

	void Push(const T& data)
	{
		if(FirstQueue.empty())
		{
			ScondQueue.push(data);
		}
		else
		{
			FirstQueue.push(data);
		}
	}
	void Pop()
	{
		if(FirstQueue.empty())
		{
			while(ScondQueue.size() != 1)
			{
				FirstQueue.push(ScondQueue.front());
				ScondQueue.pop();
			}
			ScondQueue.pop();
		}
		else
		{
			while(FirstQueue.size() != 1)
			{
				ScondQueue.push(FirstQueue.front());
				FirstQueue.pop();
			}
			FirstQueue.pop();
		}
	}
	T& Top()
	{
		if(FirstQueue.empty())
		{
			return ScondQueue.back(); 
		}
		else
		{
			return FirstQueue.back();
		}
	}
	size_t Size()
	{
		if(FirstQueue.empty())
		{
			return ScondQueue.size();
		}
		else
		{
			return FirstQueue.size();
		}
	}
	bool Empty()
	{
		return FirstQueue.empty() && ScondQueue.empty();
	}
private:
	queue<T> FirstQueue;
	queue<T> ScondQueue;
};

void test()
{
	TwoQueueFromStack<int> s;
	s.Push(1);
	s.Push(2);
	s.Push(3);
	s.Push(4);
	s.Push(5);
	s.Push(6);
	cout<<"top = "<<s.Top()<<endl;
	cout<<"size = "<<s.Size()<<endl;
	cout<<"empty = "<<s.Empty()<<endl;

	s.Pop();
	s.Pop();
	s.Pop();
	cout<<"top = "<<s.Top()<<endl;
	cout<<"size = "<<s.Size()<<endl;
	cout<<"empty = "<<s.Empty()<<endl;

	s.Pop();
	s.Pop();
	s.Pop();
	cout<<"empty = "<<s.Empty()<<endl;
}
int main()
{
	test();
	return 0;
}</span></strong>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值