Problem
Given a linked list, remove the $n$-th node from the end of list and return its head.
Example:
1 | |
Note:
Given $n$ will always be valid.
Follow up:
Could you do this in one pass?
Explanation
-
We can use two pointers to solve this problem.
-
First, we create a
preandcurpointers that both point to the head. Then,curpointer movensteps forward. Now, we move bothpreandcurpointers at the same speed one step each time, untilcurpointer points to the last node. Now, we deletepre.nextby settingpre.next = pre.next.next.
Solution
1 | |