How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.
1 template<class T> 2 class StackWithMin 3 { 4 public: 5 stack() 6 { 7 stackTop = -1; 8 minStackItemIndex = -1; 9 } 10 void Push(T x) 11 { stackTop++; 12 if(stackTop>MAXN) 13 //超出栈的最大存储量; 14 else 15 { 16 stackItem[stackTop] = x; 17 if(x<Min()) 18 { 19 NextMinItem[stackTop] = minStackItemIndex; 20 minStackItemIndex = stackTop; 21 } 22 else 23 NextMinItem[stackTop] = -1; 24 } 25 } 26 void Pop() 27 { 28 if(stackTop<0) 29 ThrowException(); 30 else 31 { 32 if(stackTop == minStackItemIndex) 33 minStackItemIndex = NextMinItem[stackTop]; 34 stackTop--; 35 } 36 } 37 T Top() 38 { 39 return stackItem[stackTop]; 40 } 41 T Min() 42 { 43 if(minStackItemIndex>=0) 44 return stackItem[minStackItemIndex]; 45 else 46 return INT_MAX; 47 } 48 49 private: 50 T stackItem[MAXN]; 51 int stackTop; 52 int NextMinItem[MAXN]; 53 int minStackItemIndex; 54 55 };