题目如文章标题所示
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* slow=head,*fast=head,*pre=head;
if(head->next==NULL)return NULL;
int cnt=1;
int number=n;
while(number--&&fast->next!=NULL){
fast=fast->next;
cnt++;
}
if(cnt==n){
//说明是删除头节点
return head->next;
}
while(fast!=NULL){
slow=slow->next;
if(slow!=head->next){
pre=pre->next;
}
fast=fast->next;
}
cout<<slow->val;
//已经找到了倒数第n个结点
ListNode* q=slow;
pre->next=q->next;
delete q;
return head;
}
};