1. 程式人生 > >在常數時間內完成push,pop,getMin的棧

在常數時間內完成push,pop,getMin的棧

class GetMinStacke
{
    public:
        void push(int x)
        {
            elements.push(x);
            if (minStack.empty() || x <= minStack.top())
            {
                minStack.push(x);
            }
        }
        bool pop()
        {
            if (elements.empty())
            {
                return false;
            }

            if (elements.top() == minStack.top())
            {
                minStack.pop();
            }
            elements.pop();
            return true;
        }
        bool getMin(int &min)
        {
            if (minStack.empty())
            {
                return false;
            }
            min = minStack.top();
            return true;
        }
    private:
        stack<int> elements;
        stack<int> minStack;
};