19. 删除链表的倒数第 N 个结点


给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

 ==============================================================

使用双指针,时间复杂度O(n),空间复杂度O(1)

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* start = head;
        ListNode* end = head;
        while (n > 0&&end->next) {
            end = end->next;
            n--;
        }
        while (end->next) {
            start = start->next;
            end = end->next;
        }
        if (start->next&&n==0) {
            ListNode* d = start->next;
            start->next = d->next;
            delete d;
            return head;
        }
        if (n > 0) {
            head = start->next;
            delete start;
            return head;
        }
        return NULL;
    }
};