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

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


"test.cpp"

#include<iostream>
using namespace std;
#include<stack>

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

	void Push(const T& data)
	{
		if(PushStack.empty())
		{
			if(!PopStack.empty())
			{
				while(!PopStack.empty())
				{
					PushStack.push(PopStack.top());
					PopStack.pop();
				}
				PushStack.push(data);
			}
			else
			{
				PushStack.push(data);
			}
		}
		else
		{
			PushStack.push(data);
		}
	}
	void Pop()
	{
		if(PopStack.empty())
		{
			if(!PushStack.empty())
			{
				while(!PushStack.empty())
				{
					PopStack.push(PushStack.top());
					PushStack.pop();
				}
				PopStack.pop();
			}
			else
			{
				PopStack.pop();
			}
		}
		else
		{
				PopStack.pop();
		}
	}
	T& Front()
	{
		if(!PopStack.empty())
		{
			return PopStack.top();
		}
		else
		{
			while(!PushStack.empty())
			{
				PopStack.push(PushStack.top());
				PushStack.pop();
			}
			return PopStack.top();
		}
	}
	T& Back()
	{
		if(!PushStack.empty())
		{
			return PushStack.top();
		}
		else
		{
			while(!PopStack.empty())
			{
				PushStack.push(PopStack.top());
				PopStack.pop();
			}
			return PushStack.top();
		}
	}
	size_t Size()
	{
		if(PushStack.empty())
		{
			return PopStack.size();
		}
		else
		{
			return PushStack.size();
		}
	}
	bool Empty()
	{
		if(PushStack.empty())
		{
			return PopStack.empty();
		}
		else
		{
			return PushStack.empty();
		}
	}
private:
	stack<T> PushStack;
	stack<T> PopStack;
};

void test()
{
	TwoStackFromQueue<int> q;
	q.Push(7);
	q.Push(3);
	q.Push(2);
	q.Push(4);
	q.Push(6);
	q.Push(9);
	q.Push(0);
	cout<<"end = "<<q.Back()<<endl;
	cout<<"begin = "<<q.Front()<<endl;
	cout<<"size = "<<q.Size()<<endl;
	
	cout<<endl;

	q.Pop();
	q.Pop();
	cout<<"end = "<<q.Back()<<endl;
	cout<<"begin = "<<q.Front()<<endl;
	cout<<"size = "<<q.Size()<<endl;
}


int main()
{
	test();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值