# How to find the 3rd node from the end in a singly linked list?

Posted July 29, 2020 167 views

How to find the 3rd node from the end in a singly linked list?
i can not traverse the linked list again and i cannot traverse backward because it’s a singly linked list. So what do? This problem challenging For me please help?

×

You have Singly Linked List given,and you have to write a function that returns the value at the n’th node from the end of the Linked List.
Here is the solution:
Now you are trying to find 3rd node from end of the linked list, So let’s take n=3.
for example we have linked list A->B->C->D->null
if you’ll give input n=3 then you’ll get output as ‘B’

Let’s take look at logic,

Method : Use length of linked list
1) Calculate the length of Linked List. Let the length be len.
2) Print the (len – n + 1)th node from the beginning of the Linked List.

//Java Solution

``````void printNthFromLast(int n)
{
int len = 0;

// 1) count the number of nodes in Linked List
while (temp != null) {
temp = temp.next;
len++;
}

// check if value of n is not more than length of
if (len < n)
return;