LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

Friday, January 18, 2008

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);
}

1 comment:

  1. Love your blog and post. This page is a good reference for this question too:


    http://www.programmerinterview.com/index.php/data-structures/find-nth-to-last-element-in-a-linked-list/

    ReplyDelete

Popular Posts