lionelsamrat10 / LeetCode-Solutions

Contains the solutions of all the problems, I am solving on Leetcode.
https://github.com/lionelsamrat10/LeetCode-Solutions
MIT License
2 stars 1 forks source link

155. Min Stack #49 #87

Closed Karthiks08 closed 3 years ago

Karthiks08 commented 3 years ago

class MinStack {

/** initialize your data structure here. */
Stack<Integer> st1;
Stack<Integer> st2;
public MinStack() {
    st1 = new Stack<Integer>();
    st2 = new Stack<Integer>();
}

public void push(int val) {
    if(!st2.isEmpty() && val <= st2.peek())
    {
        st2.push(val);
        st1.push(val);
    }
    else if(st2.isEmpty())
    {
        st2.push(val);
        st1.push(val);
    }
    else
        st1.push(val);
}

public void pop() {
    if(!st1.isEmpty())
    {
        int val = st1.pop();
        if(val == st2.peek())
        {
            st2.pop();
        }
    }
}

public int top() {
    return st1.peek();
}

public int getMin() {
    return st2.peek();
}

}