LeetCode 75

Delete the Middle Node of a Linked List

Problem
LC 2095
Topic
Linked List
File
official75_LC2095DeleteTheMiddleNodeOfALinkedList.java
Path
pkg5leetcode/official75/official75_LC2095DeleteTheMiddleNodeOfALinkedList.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC2095DeleteTheMiddleNodeOfALinkedList.java
Approach
Slow/fast pointers; delete node after slow.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC2095DeleteTheMiddleNodeOfALinkedList.java
1package pkg5leetcode.official75;2 3/*4 * Delete the Middle Node of a Linked List | LC 20955 * APPROACH: Slow/fast pointers; delete node after slow.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC2095DeleteTheMiddleNodeOfALinkedList {9    /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11    static class ListNode {12        int val;13        ListNode next;14        ListNode(int val) { this.val = val; }15    }16 17    static ListNode deleteMiddle(ListNode head) {18        if (head.next == null) return null;19        ListNode slow = head, fast = head, prev = null;20        while (fast != null && fast.next != null) {21            prev = slow;22            slow = slow.next;23            fast = fast.next.next;24        }25        prev.next = slow.next;26        return head;27    }28 29    static int[] toArray(ListNode head) {30        java.util.List<Integer> list = new java.util.ArrayList<>();31        while (head != null) { list.add(head.val); head = head.next; }32        return list.stream().mapToInt(Integer::intValue).toArray();33    }34 35    public static void main(String[] args) {36        ListNode h = new ListNode(1); h.next = new ListNode(3); h.next.next = new ListNode(4);37        h.next.next.next = new ListNode(7); h.next.next.next.next = new ListNode(1);38        h.next.next.next.next.next = new ListNode(2); h.next.next.next.next.next.next = new ListNode(6);39        check(java.util.Arrays.equals(toArray(deleteMiddle(h)), new int[]{1,3,4,1,2,6}), "case1");40        ListNode s = new ListNode(1); s.next = new ListNode(2); s.next.next = new ListNode(3); s.next.next.next = new ListNode(4);41        check(java.util.Arrays.equals(toArray(deleteMiddle(s)), new int[]{1,2,4}), "case2");42        System.out.println("all tests passed");43    }44 45    static void check(boolean cond, String name) {46        if (!cond) throw new AssertionError("FAILED: " + name);47        System.out.println("  PASS " + name);48    }49}