[Naive Approach] Using Two-Pass Traversal - O(n) Time and O(1) space
The basic to first traverse the entire linked list to count the total number of nodes. Once we know the total number of nodes, we can calculate the position of the middle node, which is at index n/2 (where n is the total number of nodes). Then go through the linked list again, but this time we stop right before the middle node. Once there, we modify the next pointer of the node before the middle node so that it skips over the middle node and points directly to the node after it,
Output
Original Linked List: 1 -> 2 -> 3 -> 4 -> 5 -> nullptr
Linked List after deleting the middle node: 1 -> 2 -> 4 -> 5 -> nullptr
Time Complexity: O(n). Two traversals of the linked list are needed Auxiliary Space: O(1). No extra space is needed.
[Expected Approach] One-Pass Traversal with Slow and Fast Pointers - O(n) Time and O(1) Space
The above solution requires two traversals of the linked list. The middle node can be deleted using one traversal. The idea is to use two pointers, slow_ptr, and fast_ptr. The fast pointer moves two nodes at a time, while the slow pointer moves one node at a time. When the fast pointer reaches the end of the list, the slow pointer will be positioned at the middle node. Next, you need to connect the node that comes before the middle node (prev) to the node that comes after the middle node. This effectively skips over the middle node, removing it from the list.
Output
Original Linked List: 1 -> 2 -> 3 -> 4 -> 5 -> NULL
Linked List after deleting the middle node: 1 -> 2 -> 4 -> 5 -> NULL
Time Complexity: O(n). Only one traversal of the linked list is needed Auxiliary Space: O(1). As no extra space is needed.