1+ package leetcode .medium ;
2+
3+ import dsa .linkedlist .ListNode ;
4+
5+ /**
6+ * https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/
7+ * <p>
8+ * Example 1:
9+ * Input: head = [1,3,4,7,1,2,6]
10+ * Output: [1,3,4,1,2,6]
11+ * Explanation:
12+ * The above figure represents the given linked list. The indices of the nodes are written below.
13+ * Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
14+ * We return the new list after removing this node.
15+ * <p>
16+ * Example 2:
17+ * Input: head = [1,2,3,4]
18+ * Output: [1,2,4]
19+ * Explanation:
20+ * The above figure represents the given linked list.
21+ * For n = 4, node 2 with value 3 is the middle node, which is marked in red.
22+ * <p>
23+ * Example 3:
24+ * Input: head = [2,1]
25+ * Output: [2]
26+ * Explanation:
27+ * The above figure represents the given linked list.
28+ * For n = 2, node 1 with value 1 is the middle node, which is marked in red.
29+ * Node 0 with value 2 is the only node remaining after removing node 1.
30+ */
31+ class DeleteMiddleNodeOfLinkedList {
32+
33+ public static void main (String [] args ) {
34+ ListNode head = new ListNode (1 );
35+ head .insertAtEnd (3 );
36+ head .insertAtEnd (4 );
37+ head .insertAtEnd (7 );
38+ head .insertAtEnd (1 );
39+ head .insertAtEnd (2 );
40+ head .insertAtEnd (6 );
41+
42+ head .printList ();
43+ ListNode listNode = deleteMiddle (head );
44+ listNode .printList (); // Output: [1,3,4,1,2,6]
45+ }
46+
47+ public static ListNode deleteMiddle (ListNode head ) {
48+ // If the list has only one node, return null
49+ if (head == null || head .next == null ) {
50+ return null ;
51+ }
52+
53+ ListNode slow = head ;
54+ ListNode fast = head ;
55+ ListNode prev = null ;
56+
57+ // Move fast pointer two steps and slow pointer one step
58+ while (fast != null && fast .next != null ) {
59+ fast = fast .next .next ;
60+ prev = slow ;
61+ slow = slow .next ;
62+ }
63+
64+ // Now 'slow' is pointing to the middle node
65+ // 'prev' is pointing to the node before the middle node
66+ // Remove the middle node by adjusting the 'next' pointer of the previous node
67+ prev .next = slow .next ;
68+
69+ return head ;
70+ }
71+ }
0 commit comments