LeetCode 2095: Delete the Middle Node of a Linked List Solution

Master LeetCode problem 2095 (Delete the Middle Node of a Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2095. Delete the Middle Node of a Linked List

Problem Explanation

Explanation

To delete the middle node of a linked list, we can use the two-pointer technique where one pointer moves one node at a time (slow pointer) and another pointer moves two nodes at a time (fast pointer). When the fast pointer reaches the end of the list, the slow pointer will be at the middle node. We can then remove this middle node by adjusting the pointers accordingly.

Solution Code

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

class Solution {
    public ListNode deleteMiddleNode(ListNode head) {
        if (head == null || head.next == null) {
            return null;
        }

        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        slow.next = slow.next.next;

        return dummy.next;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2095 (Delete the Middle Node of a Linked List)?

This page provides optimized solutions for LeetCode problem 2095 (Delete the Middle Node of a Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2095 (Delete the Middle Node of a Linked List)?

The time complexity for LeetCode 2095 (Delete the Middle Node of a Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2095 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2095 in Java, C++, or Python.

Back to LeetCode Solutions