# 最小栈

设计一个支持 pushpoptop 操作,并能在常数时间内检索到最小元素的栈。

 

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

 

提示:

以下错误的选项是?

## aop ### before ```c #include using namespace std; ``` ### after ```c /** * 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(); */ ``` ## 答案 ```c 其他三个都是错的 ``` ## 选项 ### A ```c class MinStack { public: /** initialize your data structure here. */ private: stack s; stack mins; public: MinStack() { while (!s.empty()) { s.pop(); } while (!mins.empty()) { mins.pop(); } } void push(int x) { if (s.empty()) { s.push(x); mins.push(x); } else { if (mins.top() >= x) { s.push(x); mins.push(x); } else { mins.push(mins.top()); s.push(x); } } } void pop() { s.pop(); mins.pop(); } int top() { return s.top(); } int getMin() { return mins.top(); } }; ``` ### B ```c class MinStack { public: /** initialize your data structure here. */ stack s; MinStack() { } void push(int x) { if (s.empty()) { s.push(x); s.push(x); } else { int temp = s.top(); s.push(x); if (x < temp) { s.push(x); } else { s.push(temp); } } } void pop() { s.pop(); s.pop(); } int top() { int temp = s.top(); s.pop(); int top = s.top(); s.push(temp); return top; } int getMin() { return s.top(); } }; ``` ### C ```c class MinStack { public: stack s; stack min; /** initialize your data structure here. */ MinStack() { } void push(int x) { s.push(x); if (min.empty() || x <= min.top()) { min.push(x); } } void pop() { if (s.top() == min.top()) min.pop(); s.pop(); } int top() { return s.top(); } int getMin() { return min.top(); } }; ```