Find the Middle of a Linked List โ Explained with Two Pointers (C++ Code + Intuition)


๐ง Problem Statement (Short): Given the head of a singly linked list, return the middle node.
If there are two middle nodes (even length), return the second one.
๐ก Approach: Two-Pointer Technique
We use two pointers โ slow
and fast
.
slow
moves one step at a time.fast
moves two steps at a time.When
fast
reaches the end,slow
will be at the middle.
๐ Why it works:
If one pointer moves twice as fast as the other, then by the time the fast one reaches the end, the slow one is halfway through.
โ๏ธ C++ Code
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head;
ListNode *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
๐ฉ Key Points to Remember
โ Always use:
while (fast != nullptr && fast->next != nullptr)
to avoid null pointer crashes.โ If the list has even number of nodes, this returns the second middle node โ which is what LeetCode expects.
โ Constant space: no extra memory used.
๐ Time and Space Complexity
Time: O(n)
Space: O(1)
slow
and fast
) and no extra data structures โ hence constant space.๐ง Analogy (optional, personal touch)
Think of two brothers running on the same track:
The younger brother (slow) takes one step at a time.
The older brother (fast) takes two steps.
When the older finishes the race, the younger is halfway there โ that's your middle.
๐งต Conclusion
This pattern is super handy and comes up in problems like:
Detecting cycles in linked lists
Finding the Kth node from the end
Splitting a list in half
Keep this technique in your DSA toolkit ๐ผ
Subscribe to my newsletter
Read articles from Abhinav Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Abhinav Kumar
Abhinav Kumar
๐ B.Tech CSE | ๐จโ๐ป Learning DSA & C++ | ๐ Building projects & writing what I learn | ๐ Currently solving LeetCode & exploring Git/GitHub