1. Introduction to Linked Lists
1.1 What is a Linked List?
A linked list is a linear data structure where elements are not stored in contiguous memory locations. Instead, each element (called a node) contains:
- Data: The actual value stored
- Pointer(s): Reference to the next (and possibly previous) node
Analogy: Think of a linked list like a treasure hunt:
- Each clue (node) contains information (data)
- Each clue also tells you where to find the next clue (pointer)
- You start at the first clue (head)
- The last clue says "End of hunt" (NULL pointer)
Visual Representation:
Array (Contiguous Memory):
┌────┬────┬────┬────┬────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘
[0] [1] [2] [3] [4]
Linked List (Non-contiguous Memory):
HEAD
↓
┌────┬────┐ ┌────┬────┐ ┌────┬────┐ ┌────┬────┐
│ 10 │ ●──┼───→│ 20 │ ●──┼───→│ 30 │ ●──┼───→│ 40 │NULL│
└────┴────┘ └────┴────┘ └────┴────┘ └────┴────┘
data next data next data next data next
1.2 Why Use Linked Lists?
Advantages:
- Dynamic Size: Can grow or shrink at runtime
- Easy Insertion/Deletion: No need to shift elements
- Memory Efficient: Allocate memory only when needed
- Flexible Structure: Can implement stacks, queues, graphs
Disadvantages:
- No Random Access: Must traverse from beginning
- Extra Memory: Requires space for pointers
- Sequential Access: Slower than arrays for direct access
- Cache Performance: Poor cache locality
1.3 Types of Linked Lists
1. Singly Linked List
HEAD → [data|next] → [data|next] → [data|NULL]
2. Doubly Linked List
HEAD ⇄ [prev|data|next] ⇄ [prev|data|next] ⇄ [prev|data|NULL]
3. Circular Linked List
HEAD → [data|next] → [data|next] → [data|next] ──┐
↑ │
└─────────────────────────────────────────────────┘
4. Circular Doubly Linked List
HEAD ⇄ [prev|data|next] ⇄ [prev|data|next] ──┐
↑ │
└────────────────────────────────────────────┘
1.4 Linked List vs Array
| Feature | Array | Linked List |
|---|---|---|
| Memory Allocation | Contiguous | Non-contiguous |
| Size | Fixed | Dynamic |
| Access Time | O(1) | O(n) |
| Insertion (beginning) | O(n) | O(1) |
| Insertion (end) | O(1) | O(n) or O(1) with tail |
| Deletion (beginning) | O(n) | O(1) |
| Memory Usage | Less (no pointers) | More (pointers) |
| Cache Performance | Better | Worse |
| Random Access | Yes | No |
No comments to display
No comments to display