Find nth element from end of linked list


This is one of popular interview question.

Java Linked List Interview Programs:


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 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.

Related posts

Add Comment