Stack Visualizer
What is the isEmpty Operation in Stack?
The isEmpty operation checks whether a stack contains any elements or not. It's a fundamental operation that helps prevent errors when trying to perform operations like pop() or peek() on an empty stack.
How Does It Work?
Consider a stack represented as an array:[] (empty) or[5, 3, 8] (with elements).
The operation simply checks if the stack's size/length is zero.
- For an empty stack [],isEmpty() returnstrue
- For a non-empty stack [5, 3, 8],isEmpty() returnsfalse
The operation simply checks if the stack's size/length is zero.
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
Example: Before popping an element, always check:
if (!stack.isEmpty()) element = stack.pop();
The isEmpty operation is a simple but crucial part of stack implementation, ensuring safe stack manipulation and preventing runtime errors.
Visualize Push, Pop, Peek, and IsEmpty operations
Stack Visualization
Stack is empty
Stack is empty
Stack isEmpty Operation Implementation
// Stack Implementation with isEmpty Operation in JavaScript
class Stack {
constructor() {
this.items = [];
this.top = -1;
}
// Push operation
push(element) {
this.items[++this.top] = element;
console.log(`Pushed: ${element}`);
}
// Pop operation
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow - Cannot pop from empty stack");
return -1;
}
return this.items[this.top--];
}
// Check if stack is empty
isEmpty() {
const empty = this.top === -1;
console.log(`Stack is ${empty ? "empty" : "not empty"}`);
return empty;
}
// Display stack
display() {
console.log("Current Stack:", this.items.slice(0, this.top + 1));
}
}
// Usage
const stack = new Stack();
console.log("Initial stack check:");
stack.isEmpty(); // true
stack.push(10);
stack.push(20);
stack.display();
stack.isEmpty(); // false
stack.pop();
stack.pop();
stack.isEmpty(); // true