攻克名企面试题,剑指心仪offer!——题目4 用栈实现队列


        你还在为找不到心仪的offer发愁吗?还在为面试担心吗?和我一起,提起剑来,攻克面试的种种难关!直指心仪offer!!!



题目4:请用两个栈实现队列的出队、入队

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

题目4 用两个栈实现队列

问题描述:
用两个栈实现队列

template <class T>
class myqueue
{

public:
	myqueue(void)
	{}
	~myqueue(void)
	{}

public:
	void myqueuepushback(T x);
	T myqueuedeletefront();


	void show()
	{
		while (st1.size() != 0)
		{
			T num = st1.top();
			st1.pop();
			st2.push(num);
		}
		while (st2.size() != 0)
		{
			T num = st2.top();
			st2.pop();
			cout << num << " ";
		}
		cout << endl;
	}

private:

	stack<T>  st1;
	stack<T>  st2;
};

//入队
template <class T>
void myqueue<T>::myqueuepushback(const T x)
{
	st1.push(x);
}

//出队
template <class T>
T myqueue<T>::myqueuedeletefront()
{
	if (0 == st2.size())
	{
		while (st1.size() != 0)
		{
			T& num = st1.top();
			st1.pop();
			st2.push(num);
		}
	}
	if (0 == st2.size())
		throw new exception("queue is empty");

	T q = st2.top();
	st2.pop();
	return q;
}


int main()
{
	myqueue<int> qu;
	qu.myqueuepushback(1);
	qu.myqueuepushback(2);
	qu.myqueuepushback(3);
	qu.myqueuepushback(4);
	qu.myqueuepushback(5);
	qu.myqueuepushback(6);
	try
	{
		/*qu.myqueuedeletefront();
		qu.myqueuedeletefront();
		qu.myqueuedeletefront();
		qu.myqueuedeletefront();
		qu.myqueuedeletefront();
		qu.myqueuedeletefront();
		qu.myqueuedeletefront();*/   当为空的时候再删除会出错

	}
	catch (exception *pe)
	{
		cout << pe -> what() << endl;
	}
	

	qu.show();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值