Using Stacks

Not Started

A last-in-first-out (LIFO) structure. Push items on, pop them off in reverse order. Four core operations: push (add to top), pop (remove from top), peek (look at top without removing), and isEmpty (check if stack has elements).

When to Use

Reversing a subset: Collect elements in order, pop them out reversed. Useful for reversing only the vowels in a string while keeping consonants in place.
Bracket matching: Push openers, pop and compare when you hit a closer. If the stack is empty at the end, everything matched.
Undo / backtrack: Push state changes onto the stack, pop to revert to the previous state.
Nested processing: When you encounter nested structures (e.g. nested parentheses, recursive expressions), push context and pop when you close a level.

Create a Stack

stack = []  # use a list as a stack
vector<int> stack;  // use vector as stack
var stack = new Stack<int>();  // Stack<T> class
Stack<Integer> stack = new Stack<>();  // Stack class

Push (Add to Top)

stack.append(5)  # push 5 onto stack
stack.push_back(5);  // push 5 onto stack
stack.Push(5);  // push 5 onto stack
stack.push(5);  // push 5 onto stack

Pop (Remove from Top)

top = stack.pop()  # removes and returns top element
stack.pop_back();  // removes top element
int top = stack.back();  // get before popping if needed
int top = stack.Pop();  // removes and returns top element
int top = stack.pop();  // removes and returns top element

Peek / Top (View Without Removing)

top = stack[-1]  # view top element without removing
int top = stack.back();  // view top element without removing
int top = stack.Peek();  // view top element without removing
int top = stack.peek();  // view top element without removing

Check if Empty

if not stack:      # true if empty
    print("empty")
if len(stack) == 0:  # alternative check
    print("empty")
if (stack.empty())     // true if empty
    cout << "empty";
if (stack.size() == 0)  // alternative check
    cout << "empty";
if (stack.Count == 0)  // true if empty
    Console.WriteLine("empty");
if (stack.isEmpty())  // true if empty
    System.out.println("empty");

Get Size

len(stack)  # number of elements
stack.size();  // number of elements
stack.Count;  // number of elements (property)
stack.size();  // number of elements