Middle of Linked List


876. Middle of the Linked List – LeetCode


Problem Statement

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.


Examples

Example 1:

Input: head = [1,2,3,4,5]
Output: Node with value 3
Explanation: The middle node of the list is 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: Node with value 4
Explanation: There are two middle nodes (3 and 4), and we return the second one.

Constraints


Intuition

To find the middle node of a linked list efficiently, we can use the fast and slow pointer technique:

When the fast pointer reaches the end, the slow pointer will be at the middle of the list.


Approach: Fast and Slow Pointer

  1. Initialize two pointers: slow = head, fast = head.

  2. Traverse the list:

    • Move slow one step.

    • Move fast two steps.

  3. Stop when fast == null or fast.next == null.

  4. Return the slow pointer (it will point to the middle).


Java Code

class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        return slow;
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(1)
Explanation One traversal using two pointers, no extra space used.

Dry Run

Input:

head = [1,2,3,4,5]

Pointers Progress:

Iteration fast → slow →
Init 1 1
1 3 2
2 5 3
3 null stop

Output: Node with value 3


Alternate Approach

Array-based solution (less efficient):

public ListNode middleNode(ListNode head) {
    List<ListNode> list = new ArrayList<>();
    while (head != null) {
        list.add(head);
        head = head.next;
    }
    return list.get(list.size() / 2);
}

Time: O(n), Space: O(n)


Conclusion

This problem is a classic example of the fast and slow pointer pattern, often used in linked list problems for:

It offers an elegant O(n) time and O(1) space solution.