1 #include"iostream" 2 #include"stdio.h" 3 using namespace std; 4 5 const int MAXN=1000; 6 const int INF=10000000; 7 8 template<typename T>class StackWithMin 9 { 10 public: 11 void push(const T& value); 12 void pop(); 13 T min(); 14 private: 15 int mSize=-1; 16 int minNum=INF; 17 T* mData=new T[MAXN]; 18 T* mMin=new T[MAXN]; 19 }; 20 21 template<typename T> void StackWithMin<T>::push(const T& value) 22 { 23 mData[++mSize]=value; 24 if(value<minNum) 25 { 26 minNum=value; 27 } 28 mMin[mSize]=minNum; 29 } 30 31 template<typename T>void StackWithMin<T>::pop() 32 { 33 if(mSize<0) 34 { 35 cout<<"stack is empty!"<<endl; 36 return; 37 } 38 mSize--; 39 } 40 41 template<typename T>T StackWithMin<T>::min() 42 { 43 if(mSize<0) 44 { 45 cout<<"stack is empty!"<<endl; 46 return INF; 47 } 48 return mMin[mSize]; 49 } 50 51 int main() 52 { 53 StackWithMin<double> s; 54 s.push(3); 55 cout<<s.min()<<endl; 56 s.push(4); 57 cout<<s.min()<<endl; 58 s.push(2); 59 cout<<s.min()<<endl; 60 s.push(1); 61 cout<<s.min()<<endl; 62 s.pop(); 63 cout<<s.min()<<endl; 64 s.pop(); 65 cout<<s.min()<<endl; 66 s.pop(); 67 cout<<s.min()<<endl; 68 s.pop(); 69 cout<<s.min()<<endl; 70 s.pop(); 71 cout<<s.min()<<endl; 72 73 return 0; 74 }
相关文章: