Introduction
The Stack is one of the most basic and important data structures in DSA. Interviewers love stack questions because they test your understanding of order, constraints, and control flow.
In simple terms, a stack works on the rule: Last In, First Out (LIFO).
Real-World Meaning of Stack
Think of a stack of plates:
You place a plate on top
You remove the top plate first
You cannot remove a plate from the middle. This exact behavior is followed by a stack.
What is a Stack?
A Stack is a linear data structure where:
Insertion happens at the top
Deletion also happens from the top
Basic Stack Operations
Push – add an element
Pop – remove the top element
Peek / Top – see the top element
isEmpty – check if stack is empty
Before vs After Example
Push Operation
Before: [10, 20]
Push 30
After: [10, 20, 30]
Pop Operation
Before: [10, 20, 30]
Pop
After: [10, 20]
What Interviewers Are Testing
When interviewers ask stack implementation, they check:
Can you control insertion and deletion order?
Do you handle overflow and underflow?
Do you understand memory usage differences?
Implement Stack Using Array
Idea in Simple Words
Use an array to store elements
Maintain an index called
toptopalways points to the last inserted element
Step-by-Step Logic (Array Stack)
Initialize
top = -1For push:
Increment
topInsert element at
arr[top]
For pop:
Return
arr[top]Decrement
top
Common Beginner Mistakes (Array Stack)
Forgetting stack overflow check
Popping from empty stack
Mismanaging
topindex
Code: Stack Using Array
C++ Code
class Stack {
int arr[100];
int top;
public:
Stack() {
top = -1;
}
void push(int x) {
if (top == 99) {
cout << "Stack Overflow";
return;
}
arr[++top] = x;
}
int pop() {
if (top == -1) {
cout << "Stack Underflow";
return -1;
}
return arr[top--];
}
};
One-Line Logic Before Code
We use an index to track the top and move it up for push and down for pop.
Implement Stack Using Linked List
Real-World Analogy
Imagine a chain of boxes, where each box knows only about the next box. The top of the stack is the first box.
Why Use Linked List for Stack
No fixed size limitation
Dynamic memory allocation
No overflow (until memory ends)
Join the conversation! Your thoughts help the community grow.