// 解题思路: 快慢指针
// 快指针先走 K 步,然后两个指针一起,两者相差 K 步,当快指针走到末尾时,慢指针在倒数第 K 个节点的前一个。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr)
return nullptr;
auto dummy = new ListNode(-1);
dummy->next = head;
auto fast = dummy, slow = dummy;
while(n--) {
fast = fast->next;
}
while(fast->next) {
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;
return dummy->next;
}
};