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

Abhinav KumarAbhinav Kumar
2 min read

๐Ÿง  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)
Even if we skip steps, we still have to look at each node once or skip over it โ€” so traversal-based logic in linked lists = O(n)
Space: O(1)
We use only two pointers (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 ๐Ÿ’ผ

1
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