Delete the Middle Node of a List
Problem
Given the head of a singly linked list, delete the middle node and return the new head. The middle node of a list of length n is at position ⌊n/2⌋ (0-indexed). Use slow and fast pointers — fast moves twice as quickly, so when fast hits the end, slow sits at the middle.
Input
head = 5 → 8 → 1 → 3 → 9 → nullOutput
5 → 8 → 3 → 9 → nullLength 5; middle index 2 (value 1) is removed.
def delete_middle(head):
if head is None or head.next is None:
return None
slow, fast, prev = head, head, None
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = slow.next
return head
function deleteMiddle(head) {
if (!head || !head.next) return null;
let slow = head, fast = head, prev = null;
while (fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
return head;
}
class Solution {
public ListNode deleteMiddle(ListNode head) {
if (head == null || head.next == null) return null;
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
return head;
}
}
ListNode* deleteMiddle(ListNode* head) {
if (!head || !head->next) return nullptr;
ListNode *slow = head, *fast = head, *prev = nullptr;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = slow->next;
return head;
}