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
pre
andcur
pointers that both point to the head. Then,cur
pointer moven
steps forward. Now, we move bothpre
andcur
pointers at the same speed one step each time, untilcur
pointer points to the last node. Now, we deletepre.next
by settingpre.next = pre.next.next
.
Solution
1 |
|