Problem Description
Given the head of a singly linked list, remove the middle node and return the head of the modified list. The middle node is defined as the ⌊n / 2⌋th node (0-indexed) in a list of n nodes. For example, in a list of 7 nodes, the 3rd node (0-indexed) is the middle node to remove. In the case where the list only contains one node, removing the middle node results in an empty list.
Key Insights
- Use the two pointers technique (slow and fast pointers) to find the middle node in a single pass.
- Track the node previous to the slow pointer node to efficiently remove the middle node by changing the 'next' pointer.
- Handle the edge case when the list contains only one node, in which case the result is an empty list.
Space and Time Complexity
Time Complexity: O(n) because we traverse the list once. Space Complexity: O(1) as only a constant amount of extra space is used.
Solution
We use the two pointers technique where the slow pointer moves one step at a time while the fast pointer moves two steps. When the fast pointer reaches the end, the slow pointer will be at the middle node. We also maintain a pointer to the previous node of the slow pointer so we can remove the middle node by linking the previous node directly to the next node of the slow pointer. If the list only has one node, we return null since the single node is the middle node to be removed.