Middle of the Linked List

Find the middle node of a linked list in one pass using fast and slow pointers, in O(n) time and O(1) space.

Problem Statement

Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second one.

Example

Input:  1 -> 2 -> 3 -> 4 -> 5
Output: node 3

Two Pointer Approach

Move slow by one and fast by two. When fast runs off the end, slow is exactly at the middle — all in a single pass, no length precomputation needed.

Complexity

  • Time: O(n)
  • Space: O(1)

Solution Code

Python

def middleNode(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow

Java

ListNode middleNode(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
}

C++

ListNode* middleNode(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

Key Takeaways

  • Starting both at head returns the second middle for even lengths.
  • No need to count nodes first — one pass is enough.
  • This "find middle" step is reused in merge sort on lists and palindrome checks.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.