Skip to content

Latest commit

 

History

History
40 lines (33 loc) · 1.12 KB

File metadata and controls

40 lines (33 loc) · 1.12 KB

package com.thealgorithms.linkedlist;

public class DeleteMiddleNode {

public static 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; // remove middle node
    return head;
}

public static void printList(ListNode head) {
    while (head != null) {
        System.out.print(head.val + " -> ");
        head = head.next;
    }
    System.out.println("null");
}

public static void main(String[] args) {
    ListNode head = new ListNode(1);
    head.next = new ListNode(2);
    head.next.next = new ListNode(3);
    head.next.next.next = new ListNode(4);
    head.next.next.next.next = new ListNode(5);

    System.out.print("Original list: ");
    printList(head);

    head = deleteMiddle(head);
    System.out.print("After deleting middle: ");
    printList(head);
}

}