两个栈实现getMin

设计getMin功能的栈

http://www.nowcoder.com/questionTerminal/05e57ce2cd8e4a1eae8c3b0a7e9886be

两个栈实现栈内最小数据的查询,建立一个栈A存放原始数据,再利用另一个栈B存放每一次的当前栈中的最小数,当栈A要push新的数据时,首先将该数据与栈B的top值相比较,如果栈A的数据比栈B的top值小,则将该数push近栈B,否则栈B压入上一次栈顶的值,这样就记录了每一次比较的最小值。pop时也是一样栈A与栈B的top值相等时,同时pop,否则只pop栈A的top值。

#include<iostream>
#include<stack>
#include<string>

using namespace std;

class Solution{
    public:
    void push(int value){
        StackData.push(value);
        if(StackMin.empty()||value<=StackMin.top())
        {
            StackMin.push(value);
        }
        else if(value>StackMin.top())
        {
            StackMin.push(StackMin.top());
        }
    }

    void pop(){
        if(!StackData.empty())
        {
            StackData.pop();
            StackMin.pop();
        }
        else
        {
            throw out_of_range("");
        }
    }

    int top()
    {
        return StackData.top();
    }

    int getMin()
    {
        return StackMin.top();
    }

    private:
    stack<int> StackData;
    stack<int> StackMin;
};

static Solution obj;

int main()
{
    int n,value;
    string s;
    cin>>n;
    while(n--){
        cin>>s;
        if(s=="push")
        {
            cin>>value;
            obj.push(value);
        }
        else if(s=="getMin")
        {
            cout<<obj.getMin()<<endl;
        }
        else
        {
            obj.pop();
        }
    }

    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
06-20 21:22
已编辑
门头沟学院 Java
纯真的河老师在喝茶:答应了就跑啊,实习随便跑啊,别被pua了,md就是找个廉价劳动力,还平稳过度正式工,到时候跟你说没转正
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务