Design a stack with getMin function

//Programmer code interview guide: Chapter 1: Designing a stack with getMin function
 // 1_1_getMin.cpp 
#include <iostream> 
#include <stack>
 using  namespace std;

class Solution {
    stack<int> stackPush;
    stack<int> stackMin;
public:
    void push(int elem) {
        stackPush.push(elem);
        if (stackMin.size() == 0) {
            stackMin.push (element);
        } else {
            if (elem < stackMin.top()) {
                stackMin.push (element);
            }
        }
    }

    int pop() {
        int val = stackPush.top();
        stackPush.pop();
        if (val == stackMin.top()) {
            stackMin.pop();
        }
        return val;
    }

    int getMin() {
        return stackMin.top();
    }
};

int main() {
    Solution s;
    s.push(5);
    s.push(1);
    s.push(3);
    int val = s.pop();
    cout << val << endl;
    cout << s.getMin() << endl;
    cout << s.pop() << endl;
    cout << s.getMin() << endl;
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325295760&siteId=291194637