- class MinStack {
- public:
- MinStack() {
-
- }
-
- void push(int val) {
- //只要是压栈,先将元素保存到_elem中
- _elem.push(val);
-
- //如果x小于_min中栈顶的元素,将x再压入_min中
- if(_min.empty() || val <= _min.top())
- {
- _min.push(val);
- }
- }
-
- void pop() {
-
- //如果——min栈顶的元素 == 出栈的元素,_min顶的元素要移除
- if(_min.top() == _elem.top())
- {
- _min.pop();
- }
- _elem.pop();
- }
-
- int top() {
- return _elem.top();
- }
-
- int getMin() {
- return _min.top();
- }
- private:
- //保存栈中的元素
- std::stack<int> _elem;
- //保存栈的最小值
- std::stack<int> _min;
- };
-
- /**
- * Your MinStack object will be instantiated and called as such:
- * MinStack* obj = new MinStack();
- * obj->push(val);
- * obj->pop();
- * int param_3 = obj->top();
- * int param_4 = obj->getMin();
- */
解题思路: