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;
}