Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
class MinStack { public: void push(int x) { datas.push(x); if(!min_elems.empty() && min_elems.top() < x){ min_elems.push(min_elems.top()); }else{ min_elems.push(x); } } void pop() { datas.pop(); min_elems.pop(); } int top() { return datas.top(); } int getMin() { return min_elems.top(); } private: stack<int> datas; stack<int> min_elems; };
原文:http://www.cnblogs.com/zengzy/p/5059377.html