Implementation of Stack in JavaScript (original) (raw)
Last Updated : 11 Feb, 2025
A stack is a fundamental data structure in computer science that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are widely used in various applications, such as function call management, undo mechanisms, and parsing expressions.
What is a Stack?
A stack is a linear data structure that allows operations to be performed at one end, called the **top. The two primary operations are:
- **Push: Adds an element to the top of the stack.
- **Pop: Removes and returns the top element from the stack.
Extreme Conditions in a Stack
- **Stack Underflow:
- Occurs when you try to perform a pop or peek operation on an empty stack.
- Handling: Check if the stack is empty before performing these operations.
- **Stack Overflow:
- Occurs when you try to push an element into a stack that has reached its maximum capacity (in languages or implementations where the stack size is fixed).
- Handling: Check if the stack is full before performing a push operation.
Operations Performed on a Stack
- **Push: Adds an element to the top of the stack.
- **Pop: Removes and returns the top element from the stack.
- **Peek (or Top): Returns the top element without removing it.
- **isEmpty: Checks if the stack is empty.
- **Size: Returns the number of elements in the stack.
Different way Implementation of Stack in JavaScript
1. Array Implementation of a Stack In JavaScript
- In a stack implementation, we need to do push and pop operations at the same end.
- In an array, we can do both operations at the end of the array (or last element) in O(1) time. JavaScript `
class Stack { constructor() { this.items = []; }
// Push operation push(element) { this.items.push(element); }
// Pop operation pop() { if (this.isEmpty()) { return "Stack is empty"; } return this.items.pop(); }
// Peek operation peek() { if (this.isEmpty()) { return "Stack is empty"; } return this.items[this.items.length - 1]; }
// isEmpty operation isEmpty() { return this.items.length === 0; }
// Size operation size() { return this.items.length; }
// Print the stack print() { console.log(this.items); } }
// Example Usage const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.peek());
console.log(stack.pop());
console.log(stack.size());
console.log(stack.isEmpty());
stack.print();
`
Output
30 30 2 false [ 10, 20 ]
**Time Complexity: All operations in the Stack Class ( Push , Pop, Peek, isEmpty, Size,) have O(1) time complexity. print Stack()
, which is **O(n).
**Auxiliary Space: O(1) for all operations.
**2. Linked List Implementation of Stack in JavaScript
- In a stack implementation, we need to do push and pop operations at the same end.
- In a linked list, we can do both operations at the beginning of the list (or first element) in O(1) time. JavaScript `
// Node class representing each element in the stack class Node { constructor(value) { this.value = value; this.next = null; } }
// Stack class using a Linked List
class Stack {
constructor() {
this.top = null;
this.size = 0;
}
// Push operation
push(value) {
const newNode = new Node(value);
newNode.next = this.top;
this.top = newNode;
this.size++;
}
// Pop operation
pop() {
if (this.isEmpty()) {
console.log("Stack is empty!");
return null;
}
const poppedValue = this.top.value;
this.top = this.top.next;
this.size--;
return poppedValue;
}
// Peek operation
peek() {
return this.isEmpty() ? null : this.top.value;
}
// Check if the stack is empty
isEmpty() {
return this.size === 0;
}
// Returns the size of the stack
getSize() {
return this.size;
}
// Print stack elements
printStack() {
let current = this.top;
let stackValues = [];
while (current) {
stackValues.push(current.value);
current = current.next;
}
console.log("Stack:", stackValues.join(" -> "));
}
}
// Example Usage const stack = new Stack(); stack.push(10); stack.push(20); stack.push(30); stack.printStack(); console.log("Top Element:", stack.peek()); console.log("Popped Element:", stack.pop()); stack.printStack();
`
Output
Stack: 30 -> 20 -> 10 Top Element: 30 Popped Element: 30 Stack: 20 -> 10
**Time Complexity: All operations in the Stack Class ( Push , Pop, Peek, isEmpty, Size,) have O(1) time complexity.
**Auxiliary Space : O(1) for all operations
**Easy Problems on Stack in JavaScript
- Infix to Postfix
- Prefix to Infix
- Prefix to Postfix
- Postfix to Prefix
- Check for balanced parentheses
- Reverse a string using stack
**Medium Problems on Stack in JavaScript
- Mergable Stack
- Previous Smaller Element
- Next Greater Element
- Stock Span Problem
- Next Greater Frequency Element
- Delete middle of a stack
- Check if a queue can be sorted into another queue
**Hard Problems on Stack in JavaScript
- Largest Rectangular Area in a Histogram
- Sum of Max of all Subarrays
- Stack Permutations
- Length of the longest valid substring
- Find if an expression has duplicate parenthesis
Similar Reads
- Learn Data Structures with Javascript | DSA using JavaScript Tutorial JavaScript (JS) is the most popular lightweight, interpreted programming language, and might be your first preference for Client-side as well as Server-side developments. But have you thought about using JavaScript for DSA? Learning Data Structures and Algorithms can be difficult when combined with 7 min read
- Learn Algorithms with Javascript | DSA using JavaScript Tutorial This Algorithms with Javascript tutorial is designed to help you understand and implement fundamental algorithms using the versatile JavaScript programming language. Whether you are a beginner in programming or looking to enhance your algorithmic skills, this guide will walk you through essential co 15+ min read