C fast and slow pointer


  • 0
    G
    struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode * fast = head;
    struct ListNode * slow = head;
    
    while(fast && n) {
        n--;
        fast = fast->next;
    }
    
    
    if(fast == NULL) {
        free(head);
        return head->next;
    }
    
    while(fast->next != NULL) {
        slow = slow->next;
        fast = fast->next;
    }
    
    fast = slow->next;
    slow->next = slow->next->next;
    free(fast);
    
    return head;
    

    }


  • 0
    W

    Good,thanks for sharing!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.