Implementing a Stack using Arrays
- Shreyas Naphad
- Jul 17, 2024
- 1 min read
In this article, we will learn how to implement a stack data structure using arrays.
Problem Statement: Implement a stack using an array with the following operations:
Push: Add an element to the top of the stack.
Pop: Remove the top element from the stack.
Peek/Top: Get the top element of the stack without removing it.
isEmpty: Check if the stack is empty.
Example:
Let us create a stack of size 3
Stack s(3);
// Push elements to the stack
s.push(10);
s.push(20);
s.push(30);
// Get the top element
s.top(); // Output: 30
// Pop the top element
s.pop(); // Output: 30
// Check if the stack is empty
s.isEmpty(); // Output: false
Solution:
To solve this problem, we will follow these steps:
Steps to Implement:
1. Define the Stack Class:
o Create a class Stack with an array, a variable for the maximum size of the stack, and a variable for the index of the top element.
2. Initialize the Stack:
o In the constructor, initialize the array, set the maximum size, and set the top index to -1.
3. Implement Push Operation:
o Check if the stack is full. If not, add the element to the top of the stack and increment the top index.
4. Implement Pop Operation:
o Check if the stack is empty. If not, remove the top element from the stack and decrement the top index.
5. Implement Top Operation:
o Return the top element of the stack.
6. Implement isEmpty Operation:
o Check if the top index is -1.
Comments