
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).
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def deleteMiddle(self, head: ListNode) -> ListNode:
8 if not head or not head.next:
9 return None
10
11 count = 0
12 temp = head
13 while temp:
14 count += 1
15 temp = temp.next
16
17 mid = count // 2
18 temp = head
19 prev = None
20 while mid > 0:
21 prev = temp
22 temp = temp.next
23 mid -= 1
24 if prev:
25 prev.next = temp.next
26
27 return head
28This Python solution makes use of the ListNode class to represent each node. It calculates the length of the linked list, computes the position of the middle node, and then updates the links to remove it.
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.