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.
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.
Nice post! The explanation given here is also nice:
ReplyDeletehttp://www.programmerinterview.com/index.php/data-structures/find-nth-to-last-element-in-a-linked-list/