Stack
A stack is a linear data structure that follows the first-in-last-out principle. This means the last element added to the stack will be the first one removed.
A stack is similar to an array, but in a stack, you control how data is added and removed.
Dynamic or Fixed Size
A stack can be implemented as a dynamic data structure using a linked list or as a fixed size using an array.
Main Operations in a Stack
Push - Add an element to the top of the stack
Pop - Remove the element from the top of the stack
Peek - Retrieve the top element without removing it
isEmpty - Check if the stack is empty
isFull - Check if the stack is full
class Stack { constructor(maxSize = 10) { this.stack = []; this.maxSize = maxSize; } push(data) { if (this.isFull()) { console.log("Stack Overflow: Cannot add more elements."); return; } this.stack.push(data); } pop() { if (this.isEmpty()) { console.log("Stack Underflow: No elements to remove."); return null; } return this.stack.pop(); } peek() { if (this.isEmpty()) { console.log("Stack is empty."); return null; } return this.stack[this.stack.length - 1]; } print() { console.log(this.stack); } isEmpty() { return this.stack.length === 0; } isFull() { return this.stack.length === this.maxSize; } } const myStack = new Stack(5); myStack.push(1); myStack.push(2); myStack.push(3); myStack.push(4); myStack.push(5); myStack.push(6); myStack.print(); console.log(myStack.pop()); myStack.print(); console.log(myStack.peek()); console.log(myStack.isEmpty()); console.log(myStack.isFull()); //
Applications of Stacks
Expression Evaluation:
Convert infix expressions to postfix/prefix and evaluate them.
Use for handling operators and operands in mathematical expressions.
Backtracking:
- Examples: Solving a maze, navigating directories, undo operations in text editors.
Function Calls:
- Stack is used in memory management for function calls, recursion.
Parenthesis Matching:
- Validating expressions with proper opening and closing brackets.
Reverse a Data Structure:
- Reversing a string or linked list using a stack.
Browser History:
- Implementing back/forward functionality.
Undo/Redo Operations:
- Tracking changes in text editors or similar applications.
Complexity Analysis
Operation | Time Complexity | Space Complexity |
Push | O(1) | O(n) for n elements |
Pop | O(1) | O(n) for n elements |
Peek | O(1) | O(n) for n elements |
isEmpty | O(1) | O(1) |