Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
Note: It is easy to solve the problem but hard to do it in just one pass. My first solution was to declare a pointer vector and store all the pointers. However, things did not go as I thought. I think the magic of the linked list made my solution failed. It's hard to know whether you need a malloc or not.
After reviewing some solutions posted on the Internet. I found the solution to this problem is a fast-slow-pointer. The speed of two pointers should be the same but the fast pointer should always be n-steps further than the slow pointer. Therefore, when the fast go to the end of the linked list. The item that the slow pointer point to will be the n-th node that is needed to be removed.
Solution:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast;fast=head;
ListNode *slow;slow=head;
for(int i=0;i<n;++i){
fast=fast->next;
}
if(fast==NULL){
return slow->next;
}
while(true){
fast=fast->next;
if(fast == NULL){
slow->next=slow->next->next;
return head;
}
else{
slow=slow->next;
}
}
}
};