您的位置:首页 > 职场人生

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

2013-10-14 10:46 471 查看
定义栈的数据结构,要求添加一个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()
{

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: