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

【剑指offer 面试题21】包含min函数的栈

2015-06-23 14:03 555 查看
思路:

  通过增加一个辅助栈保存每个状态对应的最小值。栈实现的不完整,应该还包含empty()等常规函数。

#include <iostream>
#include <stack>
using namespace std;

template <typename T> class StackWithMin
{
public:
void push(const T& value);
void pop();
T getMin();

private:
stack<T> DataStack;
stack<T> MinStack;
};

template <typename T> void StackWithMin<T>::push(const T& value)
{
DataStack.push(value);

if(MinStack.size() == 0 || value < MinStack.top())
MinStack.push(value);
else
MinStack.push(MinStack.top());
}

template <typename T> void StackWithMin<T>::pop()
{
DataStack.pop();
MinStack.pop();
}

template <typename T> T StackWithMin<T>::getMin()
{
return MinStack.top();
}

int main()
{
StackWithMin<int> s;

cout<<"push 5"<<endl;
s.push(5);
cout<<"Min: "<<s.getMin()<<endl;

cout<<"push 3"<<endl;
s.push(3);
cout<<"Min: "<<s.getMin()<<endl;

cout<<"push 1"<<endl;
s.push(1);
cout<<"Min: "<<s.getMin()<<endl;

cout<<"pop"<<endl;
s.pop();
cout<<"Min: "<<s.getMin()<<endl;

cout<<"pop"<<endl;
s.pop();
cout<<"Min: "<<s.getMin()<<endl;

cout<<"push 10"<<endl;
s.push(10);
cout<<"Min: "<<s.getMin()<<endl;
}


测试结果:

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