19 remove nth node from end of list

fast 先走N步
slow fast然后一起走

D->1->2->3->4->5 n=2 remove 4 

1, fast move 2 stesp to node "2"
while(n--){
    fast = fast->next;
}
2, fast slow move togeter
while(fast->next){
    fast = fast->next;
    slow = slow->next;
}
when fast == "5" slow = "3"

3, slow->next = slow->next->next;


struct ListNode * removeNthFromEnd(struct ListNode* head, int n){
    if(head == NULL)
        return NULL;
    struct ListNode * fast, *slow, *tmp, *tmp2;
    struct ListNode *dummy = calloc(1, sizeof(struct ListNode));
    dummy->next = head;
    fast = slow = dummy;
    
    while(n--){
        fast = fast->next;
    }
    while(fast->next){
        fast = fast->next;
        slow = slow->next;
    }
    tmp = slow->next;   
    slow->next = slow->next->next;
    free(tmp);
    tmp2 = dummy->next;
    free(dummy);
    return tmp2;

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容