注意要分两类情况处理。虽然显得复杂,但是容易实现且不会出错。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(head==NULL||n<=0) return head;
ListNode *first=head;
ListNode *last=head;
while(n--)last=last->next;
if(last==NULL){head=head->next;return head;}//remove the first node
//remove others
while(last->next!=NULL){
first=first->next;
last=last->next;
}
//if(first->next==NULL) return NULL;
first->next=first->next->next;
return head;
}
};