栈和队列的相互模拟

1、用两个栈(s1,s2)实现一个队列(q)

基本思想:入队列的时候都进入s1; 出队列的时候分情况,若s2不为空,则直接弹出s2栈顶元素
,若s2为空,则将s1除栈底元素外依次出栈并压入s2,再弹出s1栈底元素即可。

template <typename T>
class MyQueue
{
public:
	void push(T e)
	{
		s1.push(e);
	}
	T pop()
	{
		int temp;
		if (s1.empty() && s2.empty())
			throw exception("queue is empty!");
		if(!s2.empty())
		{
			temp = s2.top();
			s2.pop();
			return temp;			
		}
		else
		{
			while(s1.size() > 1)
			{
				temp = s1.top();
				s1.pop();
				s2.push(temp);
			}
			
			temp = s1.top();
			s1.pop();
			return temp;
		}		
	}
	int empty()
	{
		if (s1.size() + s2.size() == 0)
			return 1;
		else
			return 0;
	}
	
private:
	stack<T> s1;
	stack<T> s2;	
};

2、用两个队列(q1,q2)实现一个栈(s)

基本思想:入栈的时候进入q1,q2非空的一个,若两者都为空,进入q2; 出栈的时候,非空队列除队列尾元素外依次出队列并压入另一个队列,再将前面的队列尾元素弹出即可。

template<typename T>
class MyStack
{
public:
	void push(T e)
	{
		if(!q1.empty())
		{
			q1.push(e);
		}
		else
		{
			q2.push(e);
		}		
	}	
	T pop()
	{
		T temp;
		if (q1.empty() && q2.empty())
			throw  exception("stack is empty!");

		if (!q1.empty())
		{
			while(q1.size() > 1)
			{
				temp = q1.front();
				q1.pop();
				q2.push(temp);
			}
			temp = q1.front();
			q1.pop();
			return temp;			
		}		
		else
		{
			while(q2.size() > 1)
			{
				temp = q2.front();
				q2.pop();
				q1.push(temp);
			}
			temp = q2.front();
			q2.pop();
			return temp;			
		}
	}	
	int empty()
	{
		if (q1.size() + q2.size() == 0 )
			return 1;
		else
			return 0;
	}

private:
	queue<T> q1;
	queue<T> q2;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值