Custom Stack
About
A stack follows the LIFO (Last In, First Out) principle. The main operations in a stack are:
Push (Add an element)
Pop (Remove the top element)
Peek (View the top element)
isEmpty (Check if the stack is empty)
There are 2 ways to implement Stack i.e.
LinkedList-based Stack (Dynamic size)
Array-based Stack (Fixed size)
1. LinkedList-based Stack
Stack Data Structure
Each node contains:
A data value
A reference to the next node
Here's the Node class:
Stack Class
The CustomStack class will maintain:
A top node (points to the last added element)
The size of the stack
Core Operations
Below are the essential operations for a stack.
Push (Add Element)
Pop (Remove and Return the Top Element)
Peek (View Top Element Without Removing)
Check if Stack is Empty
Get Stack Size
Print Stack
Complete Custom Stack Implementation
Time Complexity Analysis
Push (push)
O(1)
Pop (pop)
O(1)
Peek (peek)
O(1)
Is Empty (isEmpty)
O(1)
Get Size (size)
O(1)
Print Stack (printStack)
O(n)
2. Array-based Stack
Stack Data Structure
For an array-based stack, we maintain:
An array to store elements
A top pointer to track the topmost element
A size to track the number of elements
Stack Class
Core Operations
Push (Add Element)
Pop (Remove and Return the Top Element)
Peek (View Top Element Without Removing)
Check if Stack is Empty
Get Stack Size
Print Stack
Complete Custom Stack Implementation
Time Complexity Analysis
Push (push)
O(1)
Pop (pop)
O(1)
Peek (peek)
O(1)
Is Empty (isEmpty)
O(1)
Get Size (size)
O(1)
Print Stack (printStack)
O(n)
Last updated