Min Stack, minstack

Source: Internet
Author: User

Min Stack, minstack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • Push (x)-Push element x onto stack.
  • Pop ()-Removes the element on top of the stack.
  • Top ()-Get the top element.
  • GetMin ()-Retrieve the minimum element in the stack.

Design and implement a stack, but the stack can return a minimum value at any time. You can apply for a stack to store the minimum values in the current stack. The same idea can solve the Min Stack and Max Stack problems.
C ++ Code:

class MinStack {private:          vector<int> mStack;         vector<int> mMinStack;         int mMinValue = 0;public:    void push(int x) {        if (mStack.size() == 0)            mMinValue = x;        else            mMinValue = mMinValue < x ? mMinValue : x;        mStack.push_back(x);        mMinStack.push_back(mMinValue);    }    void pop() {        mStack.pop_back();        mMinStack.pop_back();        mMinValue = getMin();    }    int top() {        if (mStack.size() > 0)            return mStack[mStack.size() - 1];        else            return -1;    }    int getMin() {        if (mMinStack.size() > 0)            return mMinStack[mMinStack.size() - 1];        else            return -1;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.