mth to last element in a linked list

Given a singly linked list, devise an algo to find the m-th to last
element of the list. Code it.(Ex. when m=0 the last element of the LL is
returned).

Answer:




[2] -> [3] -> [4] -> [5] -> ..... [100]
^ ^
mThToLast last --->
|----------------------|
distance = m


Node *mThToLast = head;
Node* last = head;
while ( m )
{
last = last->next;
--m;
}
while( last->next )
{
mThToLast= mThToLast->next;
last = last->next;
}


No comments: