Linked Lists
A linked list is a chain of nodes. Each node holds a value and a pointer to the next node. Inserting at the front is O(1), but reaching the 100th item means walking 100 steps.
A linked list stores items as a chain of nodes, each pointing to the next. Adding or removing at the front is instant, but reaching the middle means walking the chain. In everyday Python you'll rarely build one, but they're common in interviews because they test careful pointer handling.
Example
Reverse a linked list
Example
Find the middle (slow and fast pointers)
Move slow one step and fast two steps. When fast reaches the end, slow is in the middle. The same trick detects loops: if fast ever meets slow, there is a cycle.
Example
Key points
- Nodes hold a value and a link to the next node.
- Fast insert/remove at known positions; slow random access.
- Fast and slow pointers find the middle and detect cycles.
📝 Test yourself
1. What is the cost of inserting at the front of a linked list?
2. How do you find the middle in one pass?
3. Fill in what the last node's next pointer holds:
last.next =
