Sunday, April 1, 2012

Find nth last element from linked list


Problem : How do we find the nth element from the right of a singly linked list? Would reversing the link list and traversing n elements be the only possible solution?

Solution : Take two pointer's
1. Keep a distance of (n-1) between the two pointers.
2. Increment the first then by 1 and second also by 1
3. When second reaches end of list first is pointing to the desired node.

1 comment:

  1. Nice post! The explanation given here is also nice:


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

    ReplyDelete