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