一前一后两指针,让前面的先走,当两个指针距离超过n,后面的往前移
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(!head->next) return NULL;
ListNode *hb=head,*hf=head;
//for(int i=0;i<n;i++) hf=hf->next;
int flag=0;
while(hf->next){
hf=hf->next;
flag++;
if(flag>n){
hb=hb->next;
flag--;
}
}
if(flag<n) return hb->next;
//cout<<hb->val<<"and"<<hf->val<<endl;
hb->next=hb->next->next;
return head;
}
};
一前一后两指针,让前面的先走n步,然后前后一起移动
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head->next==NULL) return NULL;
ListNode *pb = head, *pf = head;
for(int i = 0; i < n; ++i) pf = pf->next;
if(!pf) return head->next;
while(pf->next){
pb = pb->next;
pf = pf->next;
}
pb->next = pb->next->next;
return head;
}
};