快慢指针可以一遍遍历解决
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
int index=0;
ListNode* fast=head;
ListNode* slow=head;
while(index<n && fast){
fast=fast->next;
index++;
}
if(fast==NULL) return head->next;
else{
fast=fast->next;
while(fast){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
}
return head;
}
};