Find Nth node of the linked list from the end.

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

Solution : Take two pointer , nthNode and current node
Initialize nthNode and current node to head.
Now traverse the current node till n counts. After this nthNode points to head and current to nth node from head.
Now traverse both node simultaneously till current reaches to the end of linked list.

After this current points to end and nthNode points at nthNode from end.

download (1)


package com.rrohit.algo.linkedlist;
/*
 * @author rrohit
 */
public class NthNodeFromEnd {
	
	public <T>Node<T> findNthNodeFromEnd(Node<T> head, int n) {
		
		if (head == null) {
			return null;
		}
		
		Node<T> nthNode = head, current = head;
		int count = 1;
		
		while (count < n) {
			current = current.getNext();
			if (current == null) {
				System.out.println("Inavlid n :: "+n+" size of Linked List = "+count);
				return null;
			}
			count++;
		}
		
		while (current.getNext() != null) {
			nthNode = nthNode.getNext();
			current = current.getNext();
		}
		
		return nthNode;
	}
	
	public static void main(String[] args) {
		LinkedList<Integer> list = new LinkedList<Integer>();
		for (int i=1; i<10; i++) {
			list.add(i);
		}
		list.display();
		NthNodeFromEnd nth = new NthNodeFromEnd();
		Node node = nth.findNthNodeFromEnd(list.getHead(), 10);
		System.out.println("3rd Node from End = "+node);
		System.out.println("Size = "+list.getSize());
		
	}

}

Add a Comment

Your email address will not be published. Required fields are marked *