Problem
Problem page: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Topics: Linked List, Two Pointers
Difficulty: Easy
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
Analysis
Problems like this commonly use fast and slow pointers. The fast pointer stays n steps ahead of the slow one, so when it reaches the end, the other points to the node just before the one we need to remove.
The node to delete might be head itself. It's easier to add a "dummy head" than to handle that case separately. The same trick is common in similar linked list problems.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-remove-nth-node-from-end-of-list/
