RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
两个栈实现一个队列

栈的特点:先进后出

营山ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18982081108(备注:SSL证书合作)期待与您的合作!

队列特点:先进先出

//实现两个栈实现一个队列
//每次都push到_s1中,pop从_s2,提高效率(每次不用互相倒栈)
#pragma once
#include
#include
#include
#include
using namespace std;
template
class Queue
{
public:
	void Push(const T& x)
	{
		_s1.push(x);
	}
	void Pop()
	{
		if (_s2.empty())
		{
			while (!_s1.empty())
			{
				_s2.push(_s1.top());
				_s1.pop();
			}
		}
		//断言当_s2为空时,不执行 (库中实现_s2.pop()也已断言,实不实现都行!!!)防止自己实现的栈出错
		assert(!_s2.empty());
		_s2.pop();
	}
	bool Empty()
	{
		return _s1.empty() && _s2.empty();
	}
	int Size()
	{
		return _s1.size() + _s2.size();
	}
	T& Front()
	{
		if (_s2.empty())
		{
			while (!_s1.empty())
			{
				_s2.push(_s1.top());
				_s1.pop();
			}
		}
		assert(!_s2.empty());
		return _s2.top();
	}
	T& Back()
	{
		if (_s1.empty())
		{
			while (!_s2.empty())
			{
				_s1.push(_s2.top());
				_s2.pop();
			}
		}
		assert(_s1.empty());
		return _s1.top();
	}
protected:
	stack _s1;
	stack _s2;
};
void Test1()
{
	Queue q1;
	q1.Push(1);
	q1.Push(2);
	q1.Push(3);
	q1.Push(4);
	q1.Push(5);
	q1.Push(6);
	q1.Pop();
	q1.Pop();
	q1.Pop();
	q1.Pop();
	q1.Pop();
	q1.Pop();
	//q1.Pop();
	//cout << q1.Front() << endl;
	//cout << q1.Back() << endl;
	//cout << q1.Empty() << endl;
	cout << q1.Size() << endl;
}

网页题目:两个栈实现一个队列
网页地址:http://sczitong.cn/article/peeijh.html