实现最小值栈 c++

实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

你实现的栈将支持pushpop 和 min 操作,所有操作要求都在O(1)时间内完成


class MinStack {
public:

    std::stack<int> stack1,stack2;
    MinStack() {
        // do intialization if necessary
    }
    /*
     * @param number: An integer
     * @return: nothing
     */
    void push(int number) {
        // write your code here
        stack1.push(number);
        if(stack2.empty())
            stack2.push(number);
        else if( number  <= stack2.top())
            stack2.push(number);
    }
    /*
     * @return: An integer
     */
    int pop() {
        int num1;
        // write your code here
        if(stack1.top()==stack2.top())
        {  
            stack1.pop(); 
            num1 =  stack2.top();
            stack2.pop();
        }else
        {
           num1 = stack1.top();
           stack1.pop();
        }
        return num1;
    }
    /*
     * @return: An integer
     */
    int min() {
        int num = stack2.top();
        return  num;
    }
};


猜你喜欢

转载自blog.csdn.net/flyxiao28/article/details/80505385