这个最简单了,就是用一个最大值栈和一个最小值栈来维护最值信息。

template<typename T>
class stack_ext : public stack<T>
{
public:
    void push(const typename stack<T>::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<T>::push(t);
    }
 
    void pop()
    {
        if (!m_sMax.empty() && stack<T>::top() == m_sMax.top())
        {
            m_sMax.pop();
        }
 
        if (!m_sMin.empty() && stack<T>::top() == m_sMin.top())
        {
            m_sMin.pop();
        }
 
        stack<T>::pop();
    }
    
    typename stack<T>::const_reference max_val() const
    {
        return m_sMax.top();
    }
 
    typename stack<T>::const_reference min_val() const
    {
        return m_sMin.top();
    }
 
private:
    stack<T> m_sMin;
    stack<T> m_sMax;
};

相关文章:

  • 2022-01-23
  • 2021-12-30
  • 2022-02-17
  • 2021-08-14
猜你喜欢
  • 2021-11-21
  • 2021-09-29
  • 2021-09-11
  • 2022-01-22
  • 2021-06-11
  • 2021-12-03
  • 2021-10-10
相关资源
相似解决方案