Delete the Middle Node of a Linked List
Implement deleteMiddle
Given the
head of a singly linked list, delete the middle node and return the head of the resulting list. If the list has two middle nodes (an even count), delete the second one.
This is finding the middle node plus one wrinkle: deleting a node means rewiring the next pointer of whatever comes before it, and a singly linked list can't look backward on its own. The optimal solution keeps a third pointer, prev, trailing one step behind slow throughout the same fast and slow pointerFast & Slow PointersTwo pointers start together but move at different speeds — typically one step vs. two steps per iteration. Because the faster one covers exactly double the distance, its position relative to the end tells you something useful about the slower one's position — here, that it's sitting on the middle. walk — so by the time fast runs out of room, prev is already exactly where it needs to be to snip the middle out. The one edge case is a single-node list, which becomes empty once its only node is removed.
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,2,4,5]
Example 2:
Input: head = [1,2,3,4,5,6]
Output: [1,2,3,5,6]
Example 3:
Input: head = [7]
Output: []
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value ≤ 10⁹ - ●
If the list has two middle nodes (an even count), delete the second one - ●
Deleting the only node in a 1-node list should leave an empty list
head =
[1, 2, 3, 4, 5]