Middle of the Linked List
Pattern: Fast and slow pointers
slow moves one node, fast moves two. When fast runs out of list, slow has covered half of it and stands on the middle (the second middle for even lengths).
The problem
Given the head of a singly linked list, return its middle node. If there are two middle nodes, return the second one.
For example, 1 → 2 → 3 → 4 → 5 gives the node 3 (printed from there as 3 → 4 → 5), and 1 → 2 → 3 → 4 → 5 → 6
gives the node 4.
The function name middleNode matches LeetCode. Use the link above for the exact statement and limits.
Think first
- How would you find the middle with two passes?
- If one pointer moves twice as fast, where is the slow one when the fast one finishes?
- For an even length, which middle does that give?
Hints
Brute force, and why it fails
Copy the nodes into an array and take index n / 2: O(n) memory. Counting first takes two passes. Fast and slow
pointers take one pass and O(1) memory.
The key insight
Whenever fast has walked 2t nodes, slow has walked t. So when fast reaches the end, slow is halfway, without ever
knowing n.
Dry run
The list is 1 → 2 → 3 → 4 → 5. slow and fast both start on 1.
The plan
slow = head, fast = head
while fast is not null and fast.next is not null:
slow = slow.next
fast = fast.next.next
return slow
Complexity
- Time
O(n)- Space
O(1)
fast covers the list once; slow covers half.
Edge cases
- One node: itself.
- Two nodes: the second.
- Even lengths always give the second middle with this loop.
I've built my logic, show the code
Java
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) { // fast moves 2 for every 1 of slow
slow = slow.next;
fast = fast.next.next;
}
return slow; // with two middles, this is the second
}
}C++
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) { // fast moves 2 for every 1 of slow
slow = slow->next;
fast = fast->next->next;
}
return slow; // with two middles, this is the second
}
};Python
from lib import ListNode
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
slow = fast = head
while fast is not None and fast.next is not None: # fast moves 2 for every 1 of slow
slow = slow.next
fast = fast.next.next
return slow # with two middles, this is the secondCommon mistakes
- Checking only
fast.next != null, which crashes whenfastbecomes null. - Starting
fastathead.next, which gives the first middle instead. - Returning the middle value when the question wants the node.