Find The Last M Th Item

Node* Find_Mth_Last(Node **head, int M)
{
    Node *p1, *p2;
    p1 = *head;
 
    while (M >= 0 && p1 != NULL) {                // do M+1 times
        p1 = p1->next;
        M -= 1;
    }
 
    if (M != -1) {                                              // if we can find out, M == -1, not M == 0
        printf("can't find Mth, because its shorter than M!");
        return NULL;
    }
 
    p2 = *head;
    while (p1 != NULL) {
        p1 = p1->next;
        p2 = p2->next;
    }
 
    return p2;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License