剑指Offer_编程题_21

时间:2023-03-08 19:27:56
剑指Offer_编程题_21

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
class Solution {
public:
void push(int value) {
st.push(value);
}
void pop() {
st.pop();
}
int top() {
return st.top();
}
int min() {
int min_num=st.top();
while(!st.empty()){
int tmp = st.top();
if(tmp < min_num){
min_num = tmp;
}
tmp_st.push(tmp);
pop();
}
while(!tmp_st.empty()){
st.push(tmp_st.top());
tmp_st.pop();
}
return min_num;
}
private:
stack<int>st;
stack<int>tmp_st;
};