
Sponsored
Sponsored
This approach involves traversing the list twice. In the first pass, you count the number of nodes to determine the middle node's index. In the second pass, you reach the middle node and update the links to skip it.
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(1).
1function ListNode(val, next) {
2 this.val = val === undefined ? 0 : val;
3 this.next = next === undefined ? null : next;
4}
5
6function deleteMiddle(head) {
7 if (!head || !head.next) return null;
8 let count = 0;
9 let temp = head;
10 while (temp) {
11 count++;
12 temp = temp.next;
13 }
14 let mid = Math.floor(count / 2);
15 temp = head;
16 let prev = null;
17 while (mid--) {
18 prev = temp;
19 temp = temp.next;
20 }
21 if (prev) {
22 prev.next = prev.next.next;
23 }
24 return head;
25}
26This JavaScript implementation uses the two-pass approach, counting nodes first and removing the middle by updating link pointers in the list.
This approach uses two pointers: a slow pointer and a fast pointer. The fast pointer moves twice as fast as the slow pointer. When the fast pointer reaches the end, the slow pointer will be at the middle node. We can then remove the middle node in a single pass.
Time Complexity: O(n)
Space Complexity: O(1)
1 public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
}
public class Solution {
public 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;
}
if (prev != null) {
prev.next = slow.next;
}
return head;
}
}
The C# implementation leverages the two-pointer technique to quickly reach the middle and remove it with minimal operations.