Stack Data Structure Visualization
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. Elements can only be added or removed from the top of the stack.
Key Operations:
- Push: Add an element to the top of the stack
- Pop: Remove the top element from the stack
Common Errors:
- Stack Overflow: Occurs when trying to push to a full stack
- Stack Underflow: Occurs when trying to pop from an empty stack
Applications:
- Function call management (call stack)
- Expression evaluation
- Undo/Redo operations
- Browser history navigation
Stack Implementation:
class Stack {
constructor(maxSize) {
this.items = [];
this.maxSize = maxSize;
this.top = -1;
}
push(element) {
if (this.top >= this.maxSize - 1) {
throw new Error("Stack Overflow");
}
this.items.push(element);
this.top++;
return element;
}
pop() {
if (this.top === -1) {
throw new Error("Stack Underflow");
}
this.top--;
return this.items.pop();
}
peek() {
return this.items[this.top];
}
isEmpty() {
return this.top === -1;
}
isFull() {
return this.top === this.maxSize - 1;
}
}