Remove the n-th node from the end
You get head, the first node of a linked list, and an integer n. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it, or None after the last node.
Number the nodes from the end: the last node is number 1, the one before it is number 2, and so on. Remove node number n and return the first node of the shortened list.
The node to remove can be the head itself. Then the second node becomes the new head, and a one-node list becomes empty, so you return None.
Remove the node by changing links: the nodes that stay must be the original node objects, not copies. Examples write a linked list as the list of its values: [6, 7, 8] means 6 → 7 → 8, and [] is an empty list.
head = [10, 20, 30, 40, 50], n = 2Output[10, 20, 30, 50]Counting from the end, 50 is number 1 and 40 is number 2. So 40 goes.
head = [6, 7, 8], n = 3Output[7, 8]Number 3 from the end is the head, so 7 becomes the new head.
head = [9], n = 1Output[]Removing the only node leaves an empty list, so the function returns None.
1 ≤ number of nodes ≤ 105
1 ≤ n ≤ number of nodes
Node values are integers and may repeat.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.