Middle of the Linked List
Easy
Linked ListTwo Pointers
Problem
Return the middle node of a singly linked list. If there are two middle nodes, return the second one.
Example 1
Input: [1,2,3,4,5]
Output: [3,4,5]
Example 2
Input: [1,2,3,4,5,6]
Output: [4,5,6]
Constraints
- 1 ≤ length ≤ 100
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def middleNode(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
Java
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;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Middle of the Linked List interactively → ← All solutions