Middle of the Linked List

easyLinked List13 stepsJava · Python · C++

Return the middle node (the second middle for even lengths). Move slow one step and fast two steps; when fast reaches the end, slow is in the middle.

▶ Watch the animated trace

Traced input: head = [1, 2, 3, 4, 5, 6] → [4, 5, 6]. Original problem: neetcode.io/problems/middle-of-the-linked-list

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

fast walks the list once.

Key idea

Common mistakes

Solution

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;
}
Python
def middleNode(head: Optional[ListNode]) -> Optional[ListNode]:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow
C++
ListNode* middleNode(ListNode* head) {
    ListNode *slow = head, *fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Odd length
The exact middle.
head = [1, 2, 3, 4, 5][3, 4, 5]
Single node
It is its own middle.
head = [1][1]
Two nodes
The second middle.
head = [1, 2][2]
← Linked List CycleRemove Nth Node From End of List →