Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Stack

1 topic · 28 Nov 2026
1

Stack

Data Structure

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++
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++
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