剑指offer[c++] 包含min函数的栈

剑指offer[c++] 包含min函数的栈

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

思路: 构建stack2存储最小值

class Solution {
public:
    void push(int value) {
        stack1.push(value);
        if(stack2.empty())
            stack2.push(value);
        else 
            if(stack2.top()>=value)
                stack2.push(value);
    }
    
    void pop() {
        if (stack1.top() == stack2.top())
            stack2.pop();
        stack1.pop();
        
    }
    int top() {
        return stack1.top();
        
    }
    int min() {
        return stack2.top();
        
    }
 
    
private:
    stack<int> stack1;
    stack<int> stack2; // 辅助找最小值
};

猜你喜欢

转载自blog.csdn.net/haikuotiankong7/article/details/80835577