DSA Stacks
DSA Stacks – Complete Beginner Guide
(Concept • Operations • Implementation • Examples • Complexity)
A Stack is one of the most important linear data structures in DSA.
It follows a simple rule called LIFO.
LIFO = Last In, First Out
1️⃣ What is a Stack?
A Stack is a data structure where:
-
Insertion happens at one end only (TOP)
-
Deletion happens from the same end
Real-Life Examples
-
Stack of plates 🍽️
-
Undo / Redo in editors
-
Browser back button
-
Function calls (Call Stack)
2️⃣ Stack Terminology
| Term | Meaning |
|---|---|
| Top | Points to the last element |
| Push | Insert element |
| Pop | Remove element |
| Peek / Top | View top element |
| Overflow | Stack full |
| Underflow | Stack empty |
3️⃣ Basic Stack Operations
1. Push (Insert)
Add element at the top.
2. Pop (Delete)
Remove element from the top.
3. Peek
View the top element without removing it.
4. isEmpty
Check if stack is empty.
4️⃣ Stack Representation (Array)
5️⃣ Stack Implementation Using Array (C++)
Output
6️⃣ Stack Implementation Using Linked List
7️⃣ Time Complexity of Stack Operations
| Operation | Time |
|---|---|
| Push | O(1) |
| Pop | O(1) |
| Peek | O(1) |
| Search | O(n) |
8️⃣ Stack Overflow & Underflow
Stack Overflow
Occurs when pushing into a full stack.
Stack Underflow
Occurs when popping from an empty stack.
9️⃣ Applications of Stack
✔ Function calls (Call Stack)
✔ Expression evaluation
✔ Parenthesis checking
✔ Undo / Redo operations
✔ Depth First Search (DFS)
✔ Reversing data
🔟 Stack vs Queue
| Feature | Stack | Queue |
|---|---|---|
| Principle | LIFO | FIFO |
| Insert | Push | Enqueue |
| Delete | Pop | Dequeue |
| Use case | Undo, DFS | Scheduling, BFS |
📌 Interview Questions (Stack)
Q1. What is stack?
👉 Linear data structure using LIFO
Q2. Is stack static or dynamic?
👉 Can be both
Q3. Stack overflow condition?
👉 When stack is full
Q4. Stack applications?
👉 Recursion, expression evaluation
✅ Final Summary
✔ Stack follows LIFO principle
✔ Insert & delete from same end
✔ Easy to implement
✔ O(1) operations
✔ Very important for DSA interviews
