You get the head of a linked list and a number n. Delete the nth node from the end. Return the head of the list.
Count from the end: the last node is the 1st.
Example 1:
Input: head = [6,2,9,4,7], n = 3 Output: [6,2,4,7] Explanation: The red node, 9, is the 3rd from the end. 7 is the 1st and 4 is the 2nd. After 9 goes, 2 links straight to 4.
Example 2:
Input: head = [8,5], n = 2 Output: [5] Explanation: The 2nd node from the end is the head. So the new head is the node with 5.
Example 3:
Input: head = [3], n = 1 Output: [] Explanation: Deleting the only node leaves an empty list. Return null.
Constraints:
- 1 to 30 nodes.
- Each value is between 0 and 100.
nis from 1 to the length of the list.
Follow up: Can you do it in one walk along the list, without counting its length first?
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
