剑指 Offer II 021. 删除链表的倒数第 n 个结点


https://leetcode-cn.com/problems/SLwz0R/

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
        struct ListNode* a=(struct ListNode*)malloc(sizeof(struct ListNode));//在head头前面创建个新的节点为了满足 删除的是head的头节点
        a->next=head;
        struct ListNode* front=a;
        struct ListNode* rear=a;
        while(n--){//因为sz大于等于1所有前面不判断为空
            front=front->next;
        }//使得front与rear相差n和节点 后面front走完是时,还是与rear相差n个节点
        while(front&&front->next){
            rear=rear->next;
            front=front->next;
        }
        if(!rear->next)
        return NULL;
        rear->next=rear->next->next;
        return a->next;
}