两个栈实现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;
}
全部评论

相关推荐

见见123:简历没有啥问题,是这个社会有问题。因为你刚毕业,没有工作经历,现在企业都不要没有工作经历的。社会病了。
点赞 评论 收藏
分享
“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
评论
6
收藏
分享

创作者周榜

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