The sword refers to Offer_Programming questions_21

Topic description

To define the data structure of the stack, please implement a min function in this type that can get the smallest element of the stack.
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;
};

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325183158&siteId=291194637