思路:
通过增加一个辅助栈保存每个状态对应的最小值。栈实现的不完整,应该还包含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() == || 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();
cout<<"Min: "<<s.getMin()<<endl; cout<<"push 3"<<endl;
s.push();
cout<<"Min: "<<s.getMin()<<endl; cout<<"push 1"<<endl;
s.push();
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();
cout<<"Min: "<<s.getMin()<<endl;
}
测试结果:
push
Min:
push
Min:
push
Min:
pop
Min:
pop
Min:
push
Min: