Size Operation
You'll learn how to track and return the number of elements currently stored in your stack.
What is the Size Operation?
The size operation tells you exactly how many elements are in your stack at any given moment. Think of it like checking how many plates are in your dish stack at a restaurant — you want to know the count without removing or disturbing any plates.
Why Do We Need Size?
While the IsEmpty operation tells you whether the stack has zero elements, size gives you the exact count. This is useful when:
- You need to know capacity usage
- You're processing a specific number of items
- You're debugging or logging stack state
- You want to avoid popping from an empty stack (size > 0 check)
How It Works
The size operation typically returns an integer representing the current element count. There are two common implementation approaches:
Approach 1: Counter Variable
Maintain a count variable that increments with every push and decrements with every pop. When size() is called, simply return this counter. This gives O(1) constant time performance.
Approach 2: Count on Demand
Traverse the entire underlying data structure (like a linked list) and count nodes. This approach takes O(n) linear time but doesn't require extra memory for a counter.
Most real-world implementations use Approach 1 because speed matters more than saving a single integer's worth of memory.
The Interface
After calling size(), the stack remains unchanged — it's a read-only query operation, just like peek or isEmpty.
Key Takeaway: The size operation returns the current number of elements in the stack, typically implemented with a counter variable for O(1) performance.