LeetCode 155. Min Stack

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.

Perhaps, this is the most lazy way.....I will update other methods later.

#include <iostream>
#include <stack>
using namespace std;


class MinStack{
private:
    struct value {
        int data;
        int currMin;
    };
    stack<value> nodes;
public:
    void push(int  x) {
        if(nodes.empty()) {
            nodes.push({x, x});
        } else {
            value tmp;
            tmp.data = x;
            tmp.currMin = min(x, nodes.top().currMin);
            nodes.push(tmp);
        }
    }

    void pop() {
        nodes.pop();
    }

    int top() {
        return nodes.top().data;
    }

    int getMin() {
        return nodes.top().currMin;
    }
};

int main(void) {
    MinStack myStack;
    myStack.push(1);
    myStack.push(2);
    cout << myStack.getMin() << endl;
    myStack.push(0);
    cout << myStack.getMin() << endl;
}


你可能感兴趣的:(LeetCode 155. Min Stack)