首页 > 其他 > 详细

得到栈中的最小值

时间:2021-01-12 16:44:13      阅读:37      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <stack>
using namespace std;

class GetMinStack{
public:
    void push(int x);

    void pop();

    int top();

    int getmin();
private:
    stack<int> S;
    stack<int> temp;
};

void GetMinStack::push(int x)
{
    if(S.empty())
    {
        temp.push(x);
        S.push(x);
    }
    else
    {
        if(x < temp.top())
        {
            temp.push(x);
            S.push(x);
        }
        else
        {
            temp.push(temp.top());
            S.push(x);
        }
    }
}
void GetMinStack::pop()
{
    S.pop();
    temp.pop();
}
int GetMinStack::top()
{
    return S.top();
}
int GetMinStack::getmin()
{
    return temp.top();
}

int main()
{
    GetMinStack TestStack;
    TestStack.push(-2);
    cout << TestStack.top() << endl;
    cout << TestStack.getmin() << endl;
    TestStack.push(0);
    cout << TestStack.getmin() << endl;
    TestStack.push(-6);
    cout << TestStack.getmin() << endl;
    TestStack.pop();
    cout << TestStack.getmin() << endl;
    return 0;
}

 

得到栈中的最小值

原文:https://www.cnblogs.com/11ys/p/14266531.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!