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;
Node temp = head;
// 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
// the linked list
if (len < n)
return;
temp = head;
// 2) get the (len-n+1)th node from the beginning
for (int i = 1; i < len - n + 1; i++)
temp = temp.next;
System.out.println(temp.data);
}
//printNthFromLast() function will calculate the length of linked list first,then using (len-n+1) formula it will give output for nth node from the end of linkedlist.