~使用两个栈实现一个队列(优化版)~

之前有篇博客中已经实现了这道题目,可最近回过头来仔细再看这道题时,才发现当初实现的有够挫的,竟然没有考虑好异常,导致程序有一些的漏洞:

1.空队列删除时会直接使程序崩溃;

2.空队列求队头时时会直接使程序崩溃;

3.空队列求队尾时时会直接使程序崩溃;

 

若是不懂本题的思路,可以查看我的这篇博客,http://blog.youkuaiyun.com/manongdeyipiant/article/details/70197256,在这里我就不赘述了!

 

改良版的源代码及测试用例如下:

#include <stack>

template <class T>
class Two_Stack_To_Queue
{
public:
	//插入
	void Push(const T& x)
	{
		input.push(x);
	}

	//删除
	void Pop()
	{
		if(!output.empty())
		{
			output.pop();
		}
		else
		{
			while(!input.empty())
			{
				output.push(input.top());
				input.pop();
			}

			if(!Empty())
			{
				output.pop();
			}
			else
			{
				cout<<"删除时发现该队列为空"<<endl;
			}
		}
	}

	//判空
	bool Empty()
	{
		if(!(input.empty() && output.empty()))
		{
			return false;
		}

		return true;
	}

	//队头
	void Front()
	//T& Front()
	{
		if(!Empty())
		{
			if(!output.empty())
			{
				//return output.top();
				cout<<"队头: "<<output.top()<<endl;
			}
			else
			{
				while(!input.empty())
				{
					output.push(input.top());
					input.pop();
				}

				//return output.top();
				cout<<"队头: "<<output.top()<<endl;
			}
		}
		else
		{
			cout<<"求队头时发现该队列为空"<<endl;
		}
	}

	//队尾
	void Back()
	//T& Back()
	{
		if(!Empty())
		{
			if(!input.empty())
			{
				//return input.top();
				cout<<"队尾: "<<input.top()<<endl;
			}
			else
			{
				while(!output.empty())
				{
					input.push(output.top());
					output.pop();
				}

				//return input.top();
				cout<<"队尾: "<<input.top()<<endl;
			}
		}
		else
		{
			cout<<"求队尾时发现该队列为空"<<endl;
		}
	}

	//大小
	size_t Size()
	{
		return input.size() + output.size();
	}

	//打印
	void Printf()
	{
		while(!Empty())
		{
			cout<<Front()<<" ";
			Pop();
		}

		cout<<endl;
	}
protected:
	stack<T> input;
	stack<T> output;
};

void TestTwo_Stack_To_Queue()
{
	Two_Stack_To_Queue<int> q;

	q.Push(1);
	q.Push(2);
	q.Push(3);
	q.Push(4);
	q.Push(5);
	//q.Printf();

	q.Pop();
	q.Pop();
	q.Pop();
	//q.Pop();
	//q.Pop();
	//q.Pop();

	//q.Printf();

	cout<<"Empty: "<<q.Empty()<<endl;
	//cout<<"Front: "<<q.Front()<<endl;
	//cout<<"Back: "<<q.Back()<<endl;
	q.Front();
	q.Back();
	cout<<"Size: "<<q.Size()<<endl;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值