用两个队列实现栈&用两个栈实现队列

栈和队列的相互实现一直是面试中常考的问题。下面是它们的相互实现代码,以方便大家学习交流。

  • 用两个队列实现栈
/*两个队列实现栈*/
#include <iostream>
#include <queue>
using namespace std;

template<typename T>
class my_stack
{
	private:
		queue<T> q_one;
		queue<T> q_two;
	public:
		int top()
		{
			if(!q_one.empty()) return q_one.back();
			else if(!q_two.empty()) return q_two.back();
		}
		int size()
		{
			return max(q_one.size(),q_two.size());
		}
		void push(T data)
		{
			if(!q_one.empty())  q_one.push(data);
			else  q_two.push(data);
		}
		void pop()
		{
			int res=0;
			if(!q_one.empty())
			{
				while(q_one.size()>1)
				{
					q_two.push(q_one.front());
					q_one.pop();
				}
				res=q_one.front();
				q_one.pop();
			}
			else if (!q_two.empty())
			{
				while(q_two.size()>1)
				{
					q_one.push(q_two.front());
					q_two.pop();
				}
				res=q_two.front();
				q_two.pop();
			}
		}
};

int main()
{
	my_stack<int> q;
	q.push(1);
	q.push(2);
	q.push(3);
	cout<<q.top()<<endl;
	q.pop();
	cout<<q.top()<<endl;
	q.push(4);
	cout<<q.top()<<endl;
	q.pop();
	q.pop();
	cout<<q.top()<<endl;
}


  • 用两个栈实现队列
/*两个栈实现队列*/
#include <iostream>
#include <stack>
using namespace std;
template<typename T>
class my_queue
{
	private:
		stack<T> s_push;
		stack<T> s_pop;
	public:
		void push(T data)
		{
			while(!s_pop.empty())
			{
				s_push.push(s_pop.top());
				s_pop.pop();
			}
			s_push.push(data);
		}
		void pop()
		{
			while(!s_push.empty())
			{
				s_pop.push(s_push.top());
				s_push.pop();
			}
			if(!s_pop.empty())	s_pop.pop();
		}
		int size()
		{
			return max(s_push.size(),s_pop.size());
		}
		T front()
		{
			while(!s_push.empty())
			{
				s_pop.push(s_push.top());
				s_push.pop();
			}
			if(!s_pop.empty())	return s_pop.top();
		}
		T back()
		{
			while(!s_pop.empty())
			{
				s_push.push(s_pop.top());
				s_pop.pop();
			}
			return s_push.top();
		}	
};

int main()
{
	my_queue<int> q;
	q.push(1);
	q.push(2);
	q.push(3);
	cout<<q.front()<<endl<<q.back()<<endl;
	q.pop();
	cout<<q.front()<<endl<<q.back()<<endl;
	q.push(4);
	q.pop();
	q.pop();
	cout<<q.front()<<endl<<q.back()<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值