2095. Delete the Middle Node of a Linked List
Solution
Section titled “Solution”class ListNode { val: number; next: ListNode | null; constructor(val?: number, next?: ListNode | null) { this.val = val === undefined ? 0 : val; this.next = next === undefined ? null : next; }}
function deleteMiddle(head: ListNode | null): ListNode | null { if (head?.next === null) return null;
let slow = head; let fast = head; let prev = head;
while (slow && fast && fast.next) { prev = slow; slow = slow.next;
fast = fast.next?.next; }
if (prev && slow) { prev.next = slow.next; }
return head;}
const first = new ListNode(1);const second = new ListNode(3);const third = new ListNode(4);const fourth = new ListNode(7);const fifth = new ListNode(1);const sixth = new ListNode(2);const seventh = new ListNode(6);
first.next = second;second.next = third;third.next = fourth;fourth.next = fifth;fifth.next = sixth;sixth.next = seventh;
deleteMiddle(first);