对应题目:力扣19题
解决方案:快慢指针,先让快指针走n步,然后快慢指针再同时前进。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* virtualHead=new ListNode;
virtualHead->next=head;
ListNode *fast=virtualHead,*slow=virtualHead;
n+=1;
while(n&&fast!=nullptr){
fast=fast->next;
n--;
}
while(fast!=nullptr){
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return virtualHead->next;
}
};