这个最简单了,就是用一个最大值栈和一个最小值栈来维护最值信息。
template
class stack_ext : public stack
{
public:
void push(const typename stack::value_type &t)
{
if (m_sMax.empty() || t >= m_sMax.top())
{
m_sMax.push(t);
}
if (m_sMin.empty() || t <= m_sMin.top())
{
m_sMin.push(t);
}
stack::push(t);
}
void pop()
{
if (!m_sMax.empty() && stack::top() == m_sMax.top())
{
m_sMax.pop();
}
if (!m_sMin.empty() && stack::top() == m_sMin.top())
{
m_sMin.pop();
}
stack::pop();
}
typename stack::const_reference max_val() const
{
return m_sMax.top();
}
typename stack::const_reference min_val() const
{
return m_sMin.top();
}
private:
stackm_sMin;
stackm_sMax;
};