Algo-Sim › Linked Lists

Middle of the Linked List

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Find the middle node in one pass: fast moves two steps for every one step of slow. Even lengths return the second middle.

Problem

Given the head of a singly linked list, return its middle node. When the list has an even number of nodes there are two middles; return the second one.

Constraints

Edge cases to test

Follow-up questions

How do you get the first middle on even lengths?
Start fast one node ahead (fast = head.next), or stop when fast.next.next is null.
What is this used for?
Splitting a list for merge sort, and finding the back half for the palindrome check and Reorder List.

Solution

Java

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

Python

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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *middleNode(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

More Linked Lists problems