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; }};