What I Learned Today: Implementing a Stack Using an Array in C++ (DSA)
Today, I dived into Data Structures and Algorithms by implementing a Stack using a dynamic array in C++. Here is a breakdown of what I learned, how the fundamental operations work under the hood, and my key takeaways from today's practice!
What is a Stack? (LIFO Principle)
A Stack is a linear data structure following the LIFO (Last In, First Out) principle. Think of it like a stack of plates—the last plate you put on top is the first one you take off.
In an array-based implementation, we maintain a contiguous block of memory and track the topmost element using an index variable named top.
C++ Code Implementation
#include <iostream>
using namespace std;
class Stack{
public:
int* arr;
int top;
int size;
int t;
Stack(int s){
size = s;
top = -1;
t = -1;
arr = new int[s];
}
void push(int val){
if(top == size - 1){
cout<<"Stack Overflow"<<endl;
}else{
top++;
arr[top] = val;
t = top;
}
}
void pop(){
if(top < 0){
cout<<"Stack Underflow"<<endl;
}else{
top--;
cout<<"element has been deleted"<<endl;
t = top;
}
}
void dis(){ //to display the data
while(t >= 0){
cout<<arr[t]<<endl;
t--;
}
}
void topp(){ //to print Last value
if(top < 0){
cout<<"Stack is Empty"<<endl;
}else{
cout<<arr[top]<<endl;
}
}
};
int main(){
Stack st(10);
st.push(10);
st.push(20);
st.push(30);
st.push(40);
st.push(50);
st.dis();
st.pop();
st.dis();
cout<<"last element ";st.topp();
}
Method Breakdowns
Here is how each method in my implementation functions:
Stack(int s): Constructor that dynamically allocates memory for an array of capacitysand initializestopto-1(signifying that the stack is currently empty).push(int val): Adds a new value onto the stack. Before inserting, it checks for Stack Overflow (top == size - 1). If space is available, it incrementstopand storesvalatarr[top].pop(): Removes the top element. It first checks for Stack Underflow (top < 0). If elements exist, it decrementstopto effectively delete the top element.dis(): Displays all elements currently stored in the stack from top to bottom by iterating down from indextto0.topp(): Peeks at the top element (arr[top]) without removing it, or warns that the stack is empty iftop < 0.
Console Output
50
40
30
20
10
element has been deleted
40
30
20
10
last element 40
Key Takeaways / Lessons Learned
- LIFO Concept: The last item pushed is always the first one popped, making stacks ideal for function calls, undo mechanisms, and parsing expressions.
- Index Tracking with
top: Settingtop = -1simplifies empty-state detection and array indexing. - Boundary Handling: Always checking for Stack Overflow before pushing and Stack Underflow before popping prevents out-of-bounds memory errors.
- Traversal & Display: Displaying elements sequentially highlights how data is ordered from top to bottom.
About the author
- 💻 Web Dev in progress..
Comments
Join the discussionNo comments yet. Be the first to comment.