AcWing 41. 包含min函数的栈
原题链接
简单
作者:
daniellee
,
2019-04-10 20:52:17
,
所有人可见
,
阅读 843
C++ 代码
class MinStack {
public:
/** initialize your data structure here. */
stack<int> st;
stack<int> st_dec;
MinStack() {
}
void push(int x) {
st.push(x);
if (!st_dec.empty()){
int t = st_dec.top();
if (x<t) st_dec.push(x);
}
else{
st_dec.push(x);
}
}
void pop() {
int t = st.top();
st.pop();
if (!st_dec.empty()){
if (t == st_dec.top()){
st_dec.pop();
}
}
}
int top() {
if (st.empty()) return NULL;
return st.top();
}
int getMin() {
if (st_dec.empty()) return NULL;
return st_dec.top();
}
};