链表问题里经典的双指针,一个先动,一个后动,然后同时动,无他,但手熟尔。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if(!head)
return head;
ListNode *pre = head, *end = head;
int tp = 0;
while(tp<n&&end){
tp++;
end = end->next;
}
if(tp<n)
return head;
if(tp==n&&end==NULL){
head = pre->next;
delete pre;
return head;
}else{
while(end->next){
pre = pre->next;
end = end->next;
}
ListNode *del = pre->next;
pre->next = del->next;
delete del;
return head;
}
}
};