The Middle of the Linked List problem requires finding the middle node of a singly linked list. If the list contains an even number of nodes, the second middle node is returned.

Problem

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.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

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

Output

[3,4,5] 

Solution

This solution uses the Two Pointer technique with a slow pointer and a fast pointer. The slow pointer moves one node at a time, while the fast pointer moves two nodes at a time.

When the fast pointer reaches the end of the list, the slow pointer will be positioned at the middle node. For an even-sized list, the fast pointer reaches the end after the slow pointer has moved to the second middle node.
public ListNode middleNode(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

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

Complexity

The fast pointer moves through the linked list at twice the speed of the slow pointer, and the list is traversed only once. Therefore, the time complexity is O(n).

The algorithm uses only two pointers regardless of the size of the linked list, resulting in an extra space complexity of O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion