0
0
Data-structures-theoryHow-ToBeginner ยท 3 min read

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 fast is null or fast.next is null, slow points 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

StepAction
InitializeSet slow and fast pointers to head
Move pointersMove slow by 1 node, fast by 2 nodes each loop
Check endStop when fast is null or fast.next is null
ResultSlow 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.