包含min函数的栈(剑指offer,c++)

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <stack>
using namespace std;

class Solution {
public:

    void push(int value) {
        st.push(value);
        if(smin.empty())
        {
            smin.push(value);
        }
        if(smin.top()>value)
        {
            smin.push(value);
        }
    }
    void pop() {
        if(st.top()==smin.top())
        {
            smin.pop();
        }
        st.pop();
    }
    int top() {
        return st.top();
    }
    int min() {
        return smin.top();
    }
    private :
    stack<int> st;
    stack<int> smin;
};

int main()
{
     Solution s;
     s.push(2);
     s.push(1);
     s.push(3);
     s.push(4);
     s.push(4);
     s.push(5);
     s.push(3);
     cout<<s.top()<<endl;
     cout<<s.min()<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/dshn/p/9326757.html