Tuesday, December 8, 2009

Given a singly-linked list, devise an algorithm to find the mth-to-last element of the list.

Given a singly-linked list, devise an algorithm to find the mth-to-last element of the list.

Element *findMToLastElement( Element *head, int m )
{
    Element *current, *mBehind;
    int i;

    /* Advance current m elements from beginning,
     * checking for the end of the list
     */
    current = head;
    for (i = 0; i < m; i++)
    {
       if (current->next)
       {
           current = current->next;
       } else
       {
           return NULL;
       }
    }

    /* Start mBehind at beginning and advance pointers
     * together until current hits last element
     */
    mBehind = head;
    while( current->next )
    {
       current = current->next;
       mBehind = mBehind->next;
    }

    /* mBehind now points to the element we were
    * searching for, so return it
    */
    return mBehind;
}

No comments:

Post a Comment