49

A stack is LIFO (Last In, First Out). Operations: push, pop, top/peek, isEmpty, all O(1).

Uses: function call stack, undo, browser back button, expression evaluation, balanced parentheses, DFS.

Stack removes the newest item, queue removes the oldest

Stack removes the newest item, queue removes the oldest

Balanced parentheses C++ 14 lines
bool isBalanced(string s) {
    stack<char> st;
    for (char c : s) {
        if (c == '(' || c == '{' || c == '[') st.push(c);
        else {
            if (st.empty()) return false;
            char t = st.top(); st.pop();
            if ((c == ')' && t != '(') || (c == '}' && t != '{') || (c == ']' && t != '['))
                return false;
        }
    }
    return st.empty();
}
// isBalanced("{[()]}") → true,  isBalanced("(]") → false
Stack using an array C++ 3 lines
int st[100], top = -1;
void push(int x) { if (top < 99) st[++top] = x; }      // overflow check
int  pop()       { return top >= 0 ? st[top--] : -1; } // underflow check