思路:
通过增加一个辅助栈保存每个状态对应的最小值。栈实现的不完整,应该还包含empty()等常规函数。
1 #include <iostream> 2 #include <stack> 3 using namespace std; 4 5 template <typename T> class StackWithMin 6 { 7 public: 8 void push(const T& value); 9 void pop(); 10 T getMin(); 11 12 private: 13 stack<T> DataStack; 14 stack<T> MinStack; 15 }; 16 17 template <typename T> void StackWithMin<T>::push(const T& value) 18 { 19 DataStack.push(value); 20 21 if(MinStack.size() == 0 || value < MinStack.top()) 22 MinStack.push(value); 23 else 24 MinStack.push(MinStack.top()); 25 } 26 27 template <typename T> void StackWithMin<T>::pop() 28 { 29 DataStack.pop(); 30 MinStack.pop(); 31 } 32 33 template <typename T> T StackWithMin<T>::getMin() 34 { 35 return MinStack.top(); 36 } 37 38 int main() 39 { 40 StackWithMin<int> s; 41 42 cout<<"push 5"<<endl; 43 s.push(5); 44 cout<<"Min: "<<s.getMin()<<endl; 45 46 cout<<"push 3"<<endl; 47 s.push(3); 48 cout<<"Min: "<<s.getMin()<<endl; 49 50 cout<<"push 1"<<endl; 51 s.push(1); 52 cout<<"Min: "<<s.getMin()<<endl; 53 54 cout<<"pop"<<endl; 55 s.pop(); 56 cout<<"Min: "<<s.getMin()<<endl; 57 58 cout<<"pop"<<endl; 59 s.pop(); 60 cout<<"Min: "<<s.getMin()<<endl; 61 62 cout<<"push 10"<<endl; 63 s.push(10); 64 cout<<"Min: "<<s.getMin()<<endl; 65 }
测试结果:
push 5 Min: 5 push 3 Min: 3 push 1 Min: 1 pop Min: 3 pop Min: 5 push 10 Min: 5