Find the middle element of a linked list
Problem
Return the middle node of the list. If there are two middle nodes, return the second one.
Example 1
Input: 1 → 2 → 3 → 4 → 5 Output: 3
Example 2
Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4
Also asked as: Find the middle Element of a linked list
Test cases
Case 1
Input: [1,2,3,4,5] Expected: [3,4,5]
Case 2
Input: [1,2,3,4,5,6] Expected: [4,5,6]
Case 3
Input: [1] Expected: [1]
View solutionHide solution1 approach
1. Fast/slow pointers
Time O(n)Space O(1)
When fast reaches the end, slow is at the middle (second middle for even length).
function middleNode(head) { let slow = head, fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } return slow;}