C++ | Using 2 stacks


#1
//Here minimum stack size not equal to normal stack

stack<int> s; // Normal stack for storing value
stack<int> m; // Stack for storing minimum value up to that
MinStack::MinStack() {
    stack<int>().swap(s);
    stack<int>().swap(m);
}

void MinStack::push(int x) {
    if(s.empty()) m.push(x);
    else if(x <= m.top()) m.push(x);
    s.push(x);
}

void MinStack::pop() {
    if(!s.empty() && !m.empty() && s.top() == m.top()) m.pop();
    if(!s.empty()) s.pop();
}

int MinStack::top() {
    if(!s.empty()) return s.top();
    return -1;
}

int MinStack::getMin() {
    if(!m.empty()) return m.top();
    return -1;
}

#2

bro can you please explain what have you done in Minstack() method and what is the purpose of that method, and how does swap function serve that purpose.