[Approach] Traversal and Pointer Adjustment - O(n) Time and O(1) Space
The idea is simple: find the node at the given position and remove it by updating the links of the nodes before and after it, so the list stays connected. If the node to delete is the head, we just move the head to the next node.
Step by Step Approach:
If the list is empty, there’s nothing to delete, so just return the head.
Go through the list to find the x-th node. If x is larger than the number of nodes, just return the head as it is.
If x is 1, we need to remove the head: move the head to the next node and make sure its previous link is null, then delete the old head.
For any other node, link its previous node to its next node, and if there’s a next node, link it back to the previous node, then remove the current node.
Return the head of the updated list.
Handling Deletion of Head and Last Node
Head Node: If the node to remove is the first one, we must move the head pointer to the next node. At the same time, if a next node exists, we should make sure its backward link no longer points to the old head.
Last Node: If the node to remove is the last one, we cut the link from its previous node so that the previous node becomes the new end of the list. In this case, the forward link is set to null.