?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dhead = new ListNode(0);//创建虚拟头节点
dhead->next = head;
ListNode* slow = dhead;
ListNode* fast = dhead;//双指针法
while (fast != nullptr && n--){//
fast = fast->next;
}//提前fast指针
fast = fast->next;//领先n+1步
while (fast != nullptr){
fast = fast->next;
slow = slow->next;
}//fast和slow指针一起前进
slow->next = slow->next->next;
return dhead->next;
}
};
|