What is the isEmpty Operation in Stack?
isEmpty just tells you whether there's anything on the stack at all. It exists so you can guard pop() and peek() calls: checking first avoids trying to read or remove from a stack that has nothing in it.
How Does It Work?
Consider a stack represented as an array: [ ] (empty) or [5, 3, 8] (with elements).
- For an empty stack [ ], isEmpty() returns true.
- For a non-empty stack [5, 3, 8], isEmpty() returns false.
The operation simply checks if the stack's size/length is zero. Notice it never reads any of the values — only the size line and whether there is a top at all, which is why it costs the same no matter how tall the stack gets.
Algorithm Implementation
- Check the current size/length of the stack
- Return the result :
- true if size equals 0.
- false otherwise.
Time Complexity
- O(1) constant time complexity.:
- The operation only needs to check one value (size/length) regardless of stack size.:
Practical Usage
- Prevent stack underflow errors before pop() operations.
- Check if there are elements to process.
- Validate stack state in algorithms.
- Terminate processing loops when stack becomes empty.
The isEmpty operation is a simple but crucial part of stack implementation, ensuring safe stack manipulation and preventing runtime errors.