Min Stack

一开始以为很容易,结果就发现问题了-----如果最小值被删了,岂不是得再次获得最小值???

大神之作啊!!

 1 class MinStack {
 2 private:
 3     stack<int> s1;
 4     stack<int> s2;
 5 public:
 6     void push(int x) {
 7         s1.push(x);
 8         if (s2.empty() || x <= getMin())  s2.push(x);      //桟里存的永远是当前的最小值,即使删除元素后!!!太重要了!!!    还有等于号地运用可以避免相同的元素!!! 
 9     }
10     void pop() {
11         if (s1.top() == getMin())  s2.pop();
12         s1.pop();
13     }
14     int top() {
15         return s1.top();
16     }
17     int getMin() {
18         return s2.top();
19     }
20 };
原文地址:https://www.cnblogs.com/daocaorenblog/p/4907796.html