The following code shows how to get nth last element in a linked list. It uses a queue to hold the temporary elements.
Algorithm:-
1>Make a queue of length N
2>Traverse the linked list from root
3>While traversing, en-queue first N elements
4>After this for en-queuing every element, de-queue another element.
5>When we reach the end of linked list, the last de-queued element will be the Nth last element.
Output:-
Thanks! This page has a good recursive answer too:
ReplyDeletehttp://www.programmerinterview.com/index.php/data-structures/find-nth-to-last-element-in-a-linked-list/