1 /* 2 设计包含 min 函数的栈(栈) 3 定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素。 4 要求函数 min、push 以及 pop 的时间复杂度都是 O(1)。 5 */ 6 #include <iostream> 7 #include <stack> 8 #include <cassert> 9 10 template<class T> class Stack 11 { 12 public: 13 void push(const T& t); 14 void pop(); 15 T top() const; 16 T min() const; 17 18 private: 19 std::stack<T> m_stack, min_stack; 20 }; 21 22 template<class T> 23 void Stack<T>::push(const T& t) 24 { 25 m_stack.push(t); 26 if(min_stack.empty()) 27 min_stack.push(t); 28 else if(t < min_stack.top()) 29 min_stack.push(t); 30 else 31 min_stack.push(min_stack.top()); 32 } 33 template<class T> 34 void Stack<T>::pop() 35 { 36 assert(!m_stack.empty() && !m_stack.empty()); 37 m_stack.pop(); 38 min_stack.pop(); 39 } 40 template<class T> 41 T Stack<T>::top() const 42 { 43 assert(!m_stack.empty()); 44 return m_stack.top(); 45 } 46 template<class T> 47 T Stack<T>::min() const 48 { 49 assert(!min_stack.empty()); 50 return min_stack.top(); 51 } 52 53 using namespace std; 54 int main(int argc, char const *argv[]) 55 { 56 Stack<int> s; 57 s.push(8); 58 s.push(3); 59 s.push(7); 60 s.push(4); 61 s.push(1); 62 s.push(3); 63 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 64 s.pop(); 65 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 66 s.pop(); 67 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 68 s.pop(); 69 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 70 s.pop(); 71 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 72 s.pop(); 73 cout<<"s.top = "<<s.top()<<" s.min = "<<s.min()<<endl; 74 return 0; 75 }