How to Find the Middle of a Linked List Easily
To find the middle of a linked list, use two pointers: a
slow pointer that moves one step at a time and a fast pointer that moves two steps at a time. When the fast pointer reaches the end, the slow pointer will be at the middle node.Syntax
The common approach uses two pointers: slow and fast. Initialize both at the head of the linked list. Move slow by one node and fast by two nodes in each step until fast reaches the end.
- slow: moves one node at a time
- fast: moves two nodes at a time
- When
fastisnullorfast.nextisnull,slowpoints to the middle node
python
slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next # slow now points to the middle node
Example
This example creates a linked list and finds its middle node using the two-pointer method. It prints the value of the middle node.
python
class Node: def __init__(self, value): self.value = value self.next = None def find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow # Create linked list: 1 -> 2 -> 3 -> 4 -> 5 head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) middle_node = find_middle(head) print("Middle node value:", middle_node.value)
Output
Middle node value: 3
Common Pitfalls
One common mistake is moving both pointers by one step, which just traverses the list without finding the middle efficiently. Another is not checking if fast or fast.next is null, which can cause errors.
Also, for even-length lists, this method returns the second middle node. If the first middle is needed, adjustments are required.
python
def wrong_find_middle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next return slow # This will cause an error or wrong result # Correct way: # while fast and fast.next: # slow = slow.next # fast = fast.next.next
Quick Reference
| Step | Action |
|---|---|
| Initialize | Set slow and fast pointers to head |
| Move pointers | Move slow by 1 node, fast by 2 nodes each loop |
| Check end | Stop when fast is null or fast.next is null |
| Result | Slow pointer is at the middle node |
Key Takeaways
Use two pointers moving at different speeds to find the middle efficiently.
Always check that fast and fast.next are not null to avoid errors.
For even-length lists, this method returns the second middle node by default.
Avoid moving both pointers at the same speed; it won't find the middle correctly.