Program for find n’th node from the end of a Linked List

Question: Given a Linked List and a number n, write a program that finds the value at the nth node from the end of the Linked List.

Method 1 – Use length of linked list

1.   Calculate the length of Linked List. Follow this tutorial Find Length of a Linked List data

2.   Print the (len – n + 1)th node from the beginning of the Linked List.

`for (int i = 1; i < length - nthNode + 1; i++)`

Code in Java

```package in.eyehunt.data.struc;

class Node {
int data;
Node next;
// Parameterized constructor
Node(int d) {
data = d;
next = null;
}
}
void push(int n) {
//create new node
Node newNode = new Node(n);
// move had point to new node
}
void findNthNode(int nthNode) {
int length = count();
} else if (nthNode > length) {
System.out.println("\nFinding nth node not existing in List");
} else {
for (int i = 1; i < length - nthNode + 1; i++)
findNode = findNode.next;
System.out.println("\nnth node in list from end is " + findNode.data);
}
}
//Returns count of nodes in linked list (iteration)
public int count() {
int a = 0;
while (n != null) {
n = n.next;
a++;
}
return a;
}
void printAllNodes() {
while (node != null) {
System.out.print("-> " + node.data);
node = node.next;
}
}
public static void main(String a[]) {
//create a simple linked list with 4 nodes
Time Complexity: `O(n) where n is the length of linked list.`