关键是逆向思维:当快指针遍历完,我们希望慢指针在哪里?
/**
* 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 *dummy = new ListNode(0); ////// 虚拟头节点防止访问空指针(->next->next), 凡是有可能修改头节点的都加一个虚拟头节点
dummy -> next = head;
ListNode *p = dummy, *q = dummy;
for(int i = 0; i < n+1; i ++){ // 当快指针遍历完,我们希望慢指针在前n+1个位置
q = q->next;
}
while(q){
q = q->next, p = p->next;
}
p->next = p->next->next;
return dummy->next;
}
};