Linked Lists
Linked Lists represent a sequence of nodes. In a singly linked list, each node points to the next node. In a doubly linked list, each node points to both the next and the previous node.
1. Structure: Singly vs. Doubly
Unlike arrays, linked lists do not have a fixed size and are not stored contiguously in memory.
| Feature | Singly Linked List | Doubly Linked List |
|---|---|---|
| Pointers | next only | next and prev |
| Direction | Forward only | Forward and Backward |
| Memory | Less overhead | More overhead (extra pointer per node) |
| Deletion | (need predecessor) | (if node is known) |
2. The "Runner" Technique (Fast & Slow Pointers)
This is a powerful technique for solving cycle detection and finding the middle of a list. You iterate through the list with two pointers at different speeds:
- Slow Pointer: Moves 1 step at a time.
- Fast Pointer: Moves 2 steps at a time.
Common Applications:
- Cycle Detection: If the fast pointer catches up to the slow pointer, there is a cycle.
- Middle Element: When the fast pointer reaches the end, the slow pointer will be at the middle.
3. Reusable Techniques
These patterns show up across many linked list problems and help reduce edge cases.
- Dummy Nodes: Use a placeholder head to simplify insertions and merges when the real head can change.
- Reversal Problems: Master pointer rewiring to reverse a whole list or a sublist in-place.
- Slow and Fast Pointers: Use different speeds to detect cycles, find midpoints, or split lists.
4. Recursive Problems
Many linked list problems can be solved recursively, often with cleaner code than the iterative approach (though watch out for stack overflow on long lists).
Example: Recursive Reverse
def reverse(head):
if not head or not head.next:
return head
new_head = reverse(head.next)
head.next.next = head
head.next = None
return new_head
Practice Problems
Reverse Linked List
LeetCode: https://leetcode.com/problems/reverse-linked-list/
Merge Two Sorted Lists
LeetCode: https://leetcode.com/problems/merge-two-sorted-lists/
Linked List Cycle
LeetCode: https://leetcode.com/problems/linked-list-cycle/
Beyond Cracking the Coding Interview
Design Singly Linked List
LeetCode: https://leetcode.com/problems/design-linked-list/
Linked List Copy
Given the head of a singly linked list, return a new list with the same values.
Doubly Linked List to Array
Given a non-null node from a doubly linked list (which might not be the head), return an array of values from head to tail.
Linked List Midpoint
LeetCode: https://leetcode.com/problems/middle-of-the-linked-list/
Linked List Block Reversal
LeetCode: https://leetcode.com/problems/reverse-nodes-in-k-group/
Linked List Zip
LeetCode: https://leetcode.com/problems/reorder-list/