class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head->next == nullptr) return nullptr;
auto fast = head;
for (int i = 0; i <= n; ++i) {
/*
* if 1->2->3->4->5 delete 5
* fast will be null
* if that's the case return the second node
*/
if (!fast) {
auto tmp = head;
head = head->next;
delete tmp;
return head;
}
fast = fast->next;
}
auto slow = head;
while(fast) {
fast = fast->next;
slow = slow->next;
}
auto tmp = slow->next;
slow->next = slow->next->next;
delete tmp;
return head;
}
};