题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数
(时间复杂度应为O(1))。

题解

//采用两个栈实现,其中一个栈正常压入弹出;再实现一个最小栈,保存当前栈中最小值
class Solution {
public:
    void push(int value) {
        stack1.push(value);
        if(stack2.empty() || value < stack2.top())
            stack2.push(value);
        else
            stack2.push(stack2.top());
    }
    void pop() {
        if(stack1.empty())
            throw("stack is empty.");
        stack1.pop();
        stack2.pop();
    }

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

    int min() {
        return stack2.top();
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};