[剑指offer][面试题21]包含min函数的栈

来源:互联网 发布:仿大牌的女装淘宝店 编辑:程序博客网 时间:2024/05/17 06:29

定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。

#include <stack>using namespace std;template<typename T>struct stackWithMin {private:stack<T> m_stack;stack<T> m_stMin;public:void push(const T& t);void pop();const T&  min();};template<typename T>void stackWithMin<T>:: push(const T& t){m_stack.push(t);if (m_stMin.size()==0 || t<m_stMin.top()){m_stMin.push(t);}else{m_stMin.push(m_stMin.top());}}template<typename T>void stackWithMin<T>:: pop(){m_stack.pop();m_stMin.pop();}template<typename T>const T& stackWithMin<T>::min(){assert(m_stack.size()>0 && m_stMin.size()>0);return m_stMin.top();}int main(){}