Find Nth node/element from the end of a LinkedList in java

You have given a LinkedList (not java.util.LinkedList), and a number N.

Write a program to find/print the value at the Nth node from end of a LinkedList in Java.

Solution1 (Using length of a LinkedList):

1)      Find the length of linked list.

2)      Print the (length-n+1) th node/element from starting of the linked list.



Solution2 (Using 2 Pointers):

        Maintain 2 pointers first and second. Initialize both pointers to header element.

1)      First move first pointer to n nodes from head

2)      Now move both first and second pointer until first pointer reaches end. Now second pointer will point to nth node from the end. Return the second pointer. 



Posted in data-structures and tagged , , .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">