
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
Using JavaScript, this solution employs a two-pointer approach, allowing for efficient traversal and removal of the middle node with a single pass.