小熊的博客

小熊要成长~

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

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

  • 用两个队列实现栈
/*两个队列实现栈*/
#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;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20183489/article/details/52368368
个人分类: 数据结构与算法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭