Given the head of a linked list, remove the nth node from the end of the list and return its head.
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Input: head = [1], n = 1
Output: []
Input: head = [1,2], n = 1
Output: [1]
sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= szFollow up: Could you do this in one pass?
The basic idea behind this approach is to determine the length of the linked list and then remove the (L-n+1)'th node from the beginning (where L is the length of the list). In the first pass, we calculate the total length of the linked list. Then in the second pass, we traverse the list again up to the (L-n+1)'th node and remove it.
L.We can improve our solution by using two pointers with a gap of n nodes between them. By moving both pointers simultaneously until the fast one reaches the end, the slow pointer will be just before the node we want to remove.
fast and slow both pointing to a dummy node ahead of head.fast pointer n+1 steps forward to maintain a gap of n between slow and fast.fast and slow pointers until fast pointer reaches the end.slow pointer will be at the node just before the target node. Adjust its next pointer to skip the nth node from the end.