Find nth element from end of linked list

Previous
Next

This is one of popular interview question.

Java Linked List Interview Programs:

Assumption:

We do not know size of linkedlist otherwise we can directly iterate and find (length-n)th node

Algorithm for this problem would be :

  • Use two pointer firstPtr and secondPtr and initialize both to head of linkedlist
  • Move firstPtr by n-1 nodes.
  • Increment firstPtr and secondPtr until firstPtr.next not equal to null.
  • SecondPtr will be at nth from end node.

Java program for this will be :

Logically our linkedlist look like following:

Color node represent 3rd node from last.
Run above program, you will get following output:

Please go through java interview programs for more such programs.
Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog