You are given the head of a linked list, head, and an integer n.
Remove the node that is n positions from the end of the list, counting the last node as position 1, and return the head of the resulting list.
You can assume n is always valid: it is never greater than the number of nodes in the list.
Linked List Encoding
Your function receives head as a ListNode and returns the head of the resulting list, or null if no nodes remain. The node type is provided for you, with val and next fields; you may relink the existing nodes in place.
The examples below write a list as the array of its values in order, so [1,2,3] is the list 1 -> 2 -> 3. That is only how lists are displayed; the encoding and decoding are done for you.
Examples
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Explanation: The 2nd node from the end is 4, so it is removed.
Example 2
Input: head = [1], n = 1
Output: []
Explanation: The only node is also the 1st node from the end, so the list becomes empty.
Example 3
Input: head = [1,2], n = 1
Output: [1]
Explanation: The last node, 2, is the 1st node from the end, so it is removed.
Constraints
The number of nodes in the list is in the range [1,30].
0≤Node.val≤100.
1≤n≤ the number of nodes in the list.
Loading editor...
Run checks the sample cases; Submit runs every case.
Samples 3
Custom 0
passedwrong answertime limiterrorran, no expected valuenot run