Skip to main content

Find nth node from end of list

Question : Write a program to find nth node from end of the list.


A simple solution would be - traverse the list and find its length. And then go to length-n th node.

But a better and more efficient solution is  (I got the idea- solution from geeksforgeeks website)

  1. Take two nodes nd1 and nd2
  2. Move nd1 to nth node from beginning of list
  3. Set nd2 to first node
  4. Move nd1 and nd2 one node at a time in a loop until nd1 is last node (nd1.next is null)
  5. Now nd2 is the nth node from end of list
 Here is complete code in Java.


import java.util.Scanner;
class LinkedList{
    class Node{
       int num;
       Node next;
       public Node(int n){
           num = n;
       }
       Node getNext(){
          return next;
       }
       int getNum(){
          return num;
       }
    }
    public LinkedList(){
       createList();
    }
    public void createList()
    {
       int n;
       Scanner scanner = new Scanner(System.in);
       System.out.println("First node=");
       n = scanner.nextInt();
       head = new Node(n);
       head.next = null;
       last = head;//only one node. 
    }
    Node head = null;
    Node last = null;
    void append(int n){
         Node newNode = new Node(n);
         last.next = newNode;
         last = newNode;
    }
    void print(){
       for(Node nd = head; nd.getNext()!=null;nd=nd.getNext()){
            System.out.println(nd.getNum()+" ");
       }
    }
    Node findLastFromN(int n){
        Node nd1 = head;
        Node nd2 = head;
        for(int i=0;i<n && nd1!=null;i++)
              nd1 = nd1.next;
        if(nd1==null)
           return null;
        while (nd1.next!=null){
            nd1 = nd1.next;
            nd2 = nd2.next;
        }
        return nd2;
    }    

          
  }
  class Demo{
      public static void main(String args[]){
             Scanner scanner = new Scanner(System.in);
             LinkedList list = new LinkedList();
             for(int i=0;i<10;i++){
                 System.out.println("num=");
                 int a = scanner.nextInt();
                 list.append(a);
             }
             list.print();
             System.out.println("n=");
             int n = scanner.nextInt();
             LinkedList.Node nd = list.findLastFromN(n);
             System.out.println("The nth node from last is "+nd.getNum());
      }
}

Comments