C++ stack
π C++ stack (LIFO Data Structure)
std::stack is a container adapter in the C++ STL that follows the LIFO (Last In, First Out) principle.
You can insert and remove elements only from the top.
πΉ 1. Why Use Stack?
Function call management
Undo / Redo operations
Expression evaluation
Parenthesis checking
Backtracking (DFS)
πΉ 2. Include Header
πΉ 3. Declaring a Stack
With underlying container:
πΉ 4. Basic Stack Operations
πΉ 5. Check Size and Empty
πΉ 6. Traversing a Stack
β No iterators provided
β Use copy to traverse:
πΉ 7. Stack Example: Reverse a String
Output:
πΉ 8. Stack Example: Parenthesis Checking
πΉ 9. Stack Using Array (Manual)
(STL stack preferred)
πΉ 10. Stack Time Complexity
| Operation | Complexity |
|---|---|
| push | O(1) |
| pop | O(1) |
| top | O(1) |
πΉ 11. Stack vs Vector vs List
| Feature | stack | vector | list |
|---|---|---|---|
| Access | Top only | Random | Sequential |
| Iterators | β | β | β |
| Use case | LIFO | General | Insert/delete |
β Common Mistakes
β Always check:
π Summary
Stack follows LIFO
push(),pop(),top()No iterators
Built on top of deque/vector/list
Used in recursion, parsing, undo systems
