编程之美3.7队列中取最大值操作

/*
编程之美3.7队列中取最大值操作
采用STL中的已有stack
方法:用的文中的方法3:保存栈中最大值可以简单实现
*/
#include<stack>
#include<iostream>
using namespace std;
template<typename T>
class Queue
{
public:
	void push(T data)
	{
		stackIn.push(data);
		if(stackInCopy.empty())
			stackInCopy.push(data);
		else if(stackInCopy.top()<data)
		{
			stackInCopy.push(data);
		}
		else
		{
			stackInCopy.push(stackInCopy.top());
		}
	}
	T pop()
	{
		if(stackOut.empty())
		{
			while(!stackIn.empty())
			{
				T temp=stackIn.top();
				stackIn.pop();
				stackOut.push(temp);
				stackInCopy.pop();
				if(stackOutCopy.empty())
				{
					stackOutCopy.push(temp);
				}
				else if(stackOutCopy.top()<temp)
				{
					stackOutCopy.push(temp);
				}
				else
				{
					stackOutCopy.push(stackOutCopy.top());
				}
			}
		}
		
        T result=stackOut.top();
		stackOut.pop();
		stackOutCopy.pop();
		
		return result;

	}
	T maxElement()
	{
		if(stackOutCopy.empty()&&stackInCopy.empty())
		{
			return INT_MIN;
		}
		else if(stackOutCopy.empty())
		{
			return stackInCopy.top();
		}
		else if(stackInCopy.empty())
		{
			return stackOutCopy.top();
		}
		else
		{
			return MAX(stackOutCopy.top(),stackInCopy.top());
		}
	}

private:
	T MAX(T x,T y)
	{
		if(x>y)
			return x;
		else
			return y;
	}
	stack<T> stackIn;
	stack<T> stackInCopy;
	stack<T> stackOut;
	stack<T> stackOutCopy;
};
void main()
{
	Queue<int> q;
	q.push(1);
	cout<<q.maxElement()<<endl;
	q.push(2);
	cout<<q.maxElement()<<endl;
	q.push(3);
	cout<<q.maxElement()<<endl;
	q.push(4);
	cout<<q.maxElement()<<endl;
	cout<<q.pop()<<endl;
	cout<<q.maxElement()<<endl;
	cout<<q.pop()<<endl;
	cout<<q.maxElement()<<endl;
	cout<<q.pop()<<endl;
	cout<<q.maxElement()<<endl;
	cout<<q.pop()<<endl;
	cout<<q.maxElement()<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值