Friday, September 16, 2011

Nth last element in Linked List (C++)

The following code shows how to get nth last element in a linked list. It uses a queue to hold the temporary elements.

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.


1 comment:

  1. Thanks! This page has a good recursive answer too: