Search Bhai

 

Visitors

How would you find the nth to last element in a linked list?

Sol: Have 2 pointers at the beginning of the linked list. Move ptr1 by n locations. Then start moving ptr2(which is at beginning of the list) parallel with ptr1. By the time ptr1 reaches the end of linked list, ptr2 will be at the nth last element.

Code:
void nth_last_elment(NODE *ln, int N)
{
NODE *nelement = ln, *node = ln;int i = 0 ;

while(i < N && node != NULL){
i++;
node = node->next;

}
if(i != N)
{
printf("\n Lesser than N elements in list %d \n ",N);
return ;
}
else
{
while(node != NULL)
{
node = node->next;
nelement = nelement->next;
}
}
printf("\n %dth element of link list from end is : %d " ,N,nelement->info);
}

Your Ad Here