VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-for-printing-nth-node-from-the-end-of-a-linked-list/

⇱ Java Program For Printing Nth Node From The End Of A Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program For Printing Nth Node From The End Of A Linked List

Last Updated : 23 Jul, 2025

Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.
For example, if the input is below the list and n = 3, then the output is "B".

👁 linkedlist

Method 1 (Use length of linked list) 

1) Calculate the length of the Linked List. Let the length be len. 
2) Print the (len - n + 1)th node from the beginning of the Linked List. 

Double pointer concept:

First pointer is used to store the address of the variable and the second pointer is used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass a pointer to it. And if we wish to change the value of a pointer (i. e., it should start pointing to something else), we pass the pointer to a pointer.

Below is the implementation of the above approach:


Output
35

Time complexity: O(n)

Auxiliary Space: O(1) since using constant space

Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing the following code. 

Time Complexity: O(n) where n is the length of linked list. 

Auxiliary Space: O(n) for call stack because using recursion.

Method 2 (Use two pointers) 

Maintain two pointers - the reference pointer and the main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.

Below image is a dry run of the above approach:

👁 Image


Output
Node no. 4 from last is 35 

Time Complexity: O(n) where n is the length of linked list. 

Auxiliary Space: O(1) using constant space.

Please refer complete article on Program for n'th node from the end of a Linked List for more details.

Comment