Middle of the Linked List
You're given the head of a non-empty singly linked list. Return the middle node. With an odd number of nodes there is exactly one middle; with an even number there are two, and you must return the second one. For n nodes that is the node at 0-based index n / 2, rounded down. You aren't told n, so try to find the middle in a single pass.
Examples
head = [1,2,3,4,5] returns node 3
There are 5 nodes, so the middle is the third, value 3 (index 2), with two nodes on each side. Returning it hands back the rest of the list, [3,4,5].
head = [1,2,3,4,5,6] returns node 4
There are 6 nodes, so values 3 and 4 (indices 2 and 3) are both middles. The problem asks for the second one, value 4.
Constraints
- 1 <= n <= 100
Hints
What if one pointer moved twice as fast as another through the list?
Slow and fast pointers, fast advancing two nodes per step.
Initialize slow = fast = head. While fast and fast.next are non-null, move slow by one and fast by two. When fast falls off the end, slow is at the middle (the second middle on even length).
Drill This: Your Approach First
Approach
Move slow one node and fast two nodes per step, stopping when fast is null or fast.next is null. By then slow has taken n / 2 steps (rounded down), so it sits at the middle, and on even lengths this stopping rule lands on the second middle. It's one pass with two references and no length count.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
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;
}
}class Solution:
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow