Stack
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where the last element added is the first one removed.
Fundamental Concepts
LIFO Principle (Last-In, First-Out)
Push (Add to top)
Pop (Remove from top)
LIFO (Last-In, First-Out) means the last element added to a collection is the first element to be removed.
Push
10
20
Push adds an element to the top of the stack, and its time complexity is O(1).
Pop
10
20
30
Pop removes the top element from the stack, and its time complexity is O(1).
Peek
10
20
30
40
Peek returns the top element without removing it, and its time complexity is O(1).
Search
10
20
30
40
Search must check each element from the top down, resulting in O(n) time complexity.
Complexity Analysis
| Operation | Time Complexity | Note |
|---|---|---|
| Push (Add) | O(1) | Fastest operation |
| Pop (Remove) | O(1) | Fastest operation |
| Peek (Top) | O(1) | Fastest operation |
| Search | O(n) | Slowest operation |