2095. Delete the Middle Node of a Linked List
Problem
Delete the middle node of a linked list of n nodes, the one at 0-based index ⌊n / 2⌋, and return the head (a single node becomes an empty list).
Example: 1→3→4→7→1→2→6 → 1→3→4→1→2→6; 1→2→3→4 → 1→2→4
Fast/slow pointers, but start fast two steps ahead so slow stops just before the middle (index ⌊n/2⌋), then unlink slow.next. A single node list becomes empty.
Complexity: O(n) time, O(1) space.
class Solution:
def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head.next:
return None
slow, fast = head, head.next.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
slow.next = slow.next.next
return head
assert list_vals(Solution().deleteMiddle(make_list([1, 3, 4, 7, 1, 2, 6]))) == [1, 3, 4, 1, 2, 6]
assert list_vals(Solution().deleteMiddle(make_list([1, 2, 3, 4]))) == [1, 2, 4]
assert list_vals(Solution().deleteMiddle(make_list([2, 1]))) == [2]
assert list_vals(Solution().deleteMiddle(make_list([1]))) == []
class Solution {
public ListNode deleteMiddle(ListNode head) {
if (head.next == null) return null;
ListNode slow = head, fast = head.next.next;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
slow.next = slow.next.next;
return head;
}
}
func deleteMiddle(head *ListNode) *ListNode {
if head.Next == nil {
return nil
}
slow, fast := head, head.Next.Next // slow stops just before the middle
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
slow.Next = slow.Next.Next
return head
}