19. Remove Nth Node From End of List
易错点:
- 为了防止head就是被删掉的那个节点,要设立dummy,最后返回的是newhead->next
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fast = new ListNode(-1);
ListNode* slow = fast;
ListNode* newHead = fast;
fast -> next = head;
for (int i = 0; i < n; i ++){
fast = fast -> next;
}
while (fast->next != nullptr){
fast = fast -> next;
slow = slow -> next;
}
slow->next = slow->next->next;
return newHead->next;
}
};