面试题:用两个栈实现队列,用两个队列实现栈

发布时间:2020-06-19 22:22:39 作者:zgw285763054
来源:网络 阅读:554

两个栈实现一个队列:

template<class T>
class CQueue
{
public:
	void Push(const T& element)
	{
		stack1.push(element);
	}

	void Pop()
	{
		if (stack2.empty())
		{
			while (!stack1.empty())
			{
				stack2.push(stack1.top());
				stack1.pop();
			}
		}

		if (stack2.empty())
		{
			cout<<"queue is empty"<<endl;
			assert(false);
		}

		stack2.pop();
	}

	bool Empty()
	{
		if (stack1.empty() && stack2.empty())
			return true;
		else
			return false;

	}

	T Front()
	{
		if (!stack2.empty())
		{
			return stack2.top();
		}
		else
		{
			while (!stack1.empty())
			{
				stack2.push(stack1.top());
				stack1.pop();
			}

			if (stack2.empty())
			{
				cout<<"queue is empty"<<endl;
				assert(false);
			}

			return stack2.top();
		}
	}

private:
	stack<T> stack1;
	stack<T> stack2;
};



两个队列实现一个栈:

template<class T>
class CStack
{
public:
	void Push(const T& element)
	{
		queue1.push(element);
	}

	void Pop()
	{
		if (queue1.empty())
		{
			cout<<"stack is empty"<<endl;
			assert(false);
		}

		while (queue1.size() != 1)
		{
			queue2.push(queue1.front());
			queue1.pop();
		}

		queue1.pop();

		while (!queue2.empty())
		{
			queue1.push(queue2.front());
			queue2.pop();
		}
	}

	bool Empty()
	{
		if (queue1.empty())
			return true;
		else
			return false;
	}

	T Top()
	{
		if (queue1.empty())
		{
			cout<<"stack is empty"<<endl;
			assert(false);
		}
		return queue1.back();
	}

private:
	queue<T> queue1;
	queue<T> queue2;
};


推荐阅读:
  1. 用两个队列实现一个栈
  2. 用两个栈实现一个队列

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

队列

上一篇:使用docker-compose部署LNMP环境

下一篇:Go中defer的延迟调用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》