标签:
Description:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Code:
1 class MinStack { 2 public: 3 void push(int x) { 4 m_stack.push(x); 5 if (min_num.empty() || x<min_num.top()) 6 min_num.push(x); 7 else 8 min_num.push(min_num.top()); 9 } 10 11 void pop() { 12 assert( !m_stack.empty() && !min_num.empty() ); 13 m_stack.pop(); 14 min_num.pop(); 15 } 16 17 int top() { 18 assert( !m_stack.empty() ); 19 return m_stack.top(); 20 } 21 22 int getMin() { 23 return min_num.top(); 24 } 25 private: 26 stack<int>m_stack; 27 stack<int>min_num; 28 };
标签:
原文地址:http://www.cnblogs.com/happygirl-zjj/p/4592917.html