class MinStack { public: /** initialize your data structure here. */ stack<int> stackValue; stack<int> stackmin; MinStack() { } void push(int x) { stackValue.push(x); if(stackmin.empty() || x <= stackmin.top()) //不要忘记单调栈为空的情况 stackmin.push(x); } void pop() { if (stackmin.top() == stackValue.top()) stackmin.pop();//删除栈顶元素时,如果单调栈符合条件,夜要删除掉 stackValue.pop(); } int top() { return stackValue.top(); } int getMin() { return stackmin.top(); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
来源:https://www.cnblogs.com/make-big-money/p/12309158.html