class Solution {
public:
// 1. 可以先计算出链表的总长度s,然后删除第s-n就可以了
ListNode* removeNthFromEnd(ListNode* head, int n) {
int s=0;
ListNode *p=head,*pre;
while(p!=nullptr){
s++;
p=p->next;
}
pre=p=head;
n=s-n;
if(n==0){
// 说明删除的是第0个
return head->next;
}
while(n--){
pre=p;
p=p->next;
}
// 删除p
pre->next=p->next;
return head;
}
};
双指针:
class Solution {
public:
// 使用双指针,初始化first和second距离相差n,那么当second到达尾部的时候,first+1就是需要删除的元素,first=first->next,就完成删除操作
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* first=head;
ListNode* second=head;
while(n--){
first=first->next;
}
if(first==nullptr) return head->next;
while(first->next!=nullptr){
first=first->next;
second=second->next;
}
// 删除
second->next=second->next->next;
return head;
}
};