码迷,mamicode.com
首页 > 其他好文 > 详细

131工结

时间:2020-01-31 12:44:21      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:struct   ali   called   str   get   param   code   init   ini   

class MinStack {
//变量的初始化可以在private里写
private:
    stack<int> s;
    stack<int> min;
public:
    /** initialize your data structure here. */
    //初始化就是把其全部置空
    MinStack() {
        while(!s.empty())
        {
            s.pop();
        }
        while(!min.empty())
        {
            min.pop();
        }
    }
    
    void push(int x) {
        //如果没有判空,会错误,因为 无法直接比较top
        if(s.empty())
        {
            s.push(x);
            min.push(x);
        }
        else
        {
            s.push(x);
            if(x<=min.top())
            {
                min.push(x);
            }
            else
            {
                min.push(min.top());
            }
        }
    }
    
    void pop() {
        s.pop();
        min.pop();
    }
    
    int top() {
        return s.top();
        
    }
    
    int getMin() {
        return min.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack* obj = new MinStack();
 * obj->push(x);
 * obj->pop();
 * int param_3 = obj->top();
 * int param_4 = obj->getMin();
 */

 

131工结

标签:struct   ali   called   str   get   param   code   init   ini   

原文地址:https://www.cnblogs.com/Marigolci/p/12244711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!