What is a Linked List?
A linked list is a linear data structure where elements are stored in nodes, and each node points to the next one. Unlike arrays, linked list elements are not stored in contiguous memory locations.
The Train Analogy: Think of a linked list like a train:
- •Each train car (node) contains cargo (data)
- •Each car is connected to the next car (pointer)
- •You can only move forward car by car
- •You can't jump directly to car #5 without passing through cars 1-4
Why Linked Lists Exist:
Trade-offs vs Arrays:
| Operation | Array | Linked List |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert at beginning | O(n) | O(1) |
| Insert at end | O(1)* | O(n) or O(1)** |
| Insert in middle | O(n) | O(1) if position known |
| Memory | Contiguous | Scattered |
*Amortized for dynamic arrays **O(1) if tail pointer maintained