Open In App

Java Program For Printing Nth Node From The End Of A Linked List

Last Updated : 02 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.
For example, if the input is below the list and n = 3, then the output is "B".

linkedlist

Method 1 (Use length of linked list) 

1) Calculate the length of the Linked List. Let the length be len. 
2) Print the (len - n + 1)th node from the beginning of the Linked List. 

Double pointer concept:

First pointer is used to store the address of the variable and the second pointer is used to store the address of the first pointer. If we wish to change the value of a variable by a function, we pass a pointer to it. And if we wish to change the value of a pointer (i. e., it should start pointing to something else), we pass the pointer to a pointer.

Below is the implementation of the above approach:

Java
// Simple Java program to find n'th node from end of linked list
class LinkedList {
    Node head; // head of the list

    /* Linked List node */
    class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }

    /* Function to get the nth node from the last of a
       linked list */
    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);
    }

    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);

        /* 3. Make next of new Node as head */
        new_node.next = head;

        /* 4. Move the head to point to new Node */
        head = new_node;
    }

    /*Driver program to test above methods */
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
        llist.push(20);
        llist.push(4);
        llist.push(15);
        llist.push(35);

        llist.printNthFromLast(4);
    }
} // This code is contributed by Rajat Mishra

Output
35

Time complexity: O(n)

Auxiliary Space: O(1) since using constant space

Following is a recursive C code for the same method. Thanks to Anuj Bansal for providing the following code. 

Java
static void printNthFromLast(Node head, int n)
{
    static int i = 0;

    if (head == null)
        return;
    printNthFromLast(head.next, n);

    if (++i == n)
        System.out.print(head.data);
}

// This code is contributed by rutvik_56.

Time Complexity: O(n) where n is the length of linked list. 

Auxiliary Space: O(n) for call stack because using recursion.

Method 2 (Use two pointers) 

Maintain two pointers - the reference pointer and the main pointer. Initialize both reference and main pointers to head. First, move the reference pointer to n nodes from head. Now move both pointers one by one until the reference pointer reaches the end. Now the main pointer will point to nth node from the end. Return the main pointer.

Below image is a dry run of the above approach:

Java
// Java program to find n'th
// node from end using slow and
// fast pointers

class LinkedList {
    Node head; // head of the list

    /* Linked List node */
    class Node {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }

    /* Function to get the
      nth node from end of list */
    void printNthFromLast(int n)
    {
        Node main_ptr = head;
        Node ref_ptr = head;

        int count = 0;
        if (head != null) {
            while (count < n) {
                if (ref_ptr == null) {
                    System.out.println(
                        n + " is greater than the no "
                        + " of nodes in the list");
                    return;
                }
                ref_ptr = ref_ptr.next;
                count++;
            }

            if (ref_ptr == null) {

                if (head != null)
                    System.out.println("Node no. " + n
                                       + " from last is "
                                       + head.data);
            }
            else {

                while (ref_ptr != null) {
                    main_ptr = main_ptr.next;
                    ref_ptr = ref_ptr.next;
                }
                System.out.println("Node no. " + n
                                   + " from last is "
                                   + main_ptr.data);
            }
        }
    }

    /* Inserts a new Node at front of the list. */
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);

        /* 3. Make next of new Node as head */
        new_node.next = head;

        /* 4. Move the head to point to new Node */
        head = new_node;
    }

    /*Driver program to test above methods */
    public static void main(String[] args)
    {
        LinkedList llist = new LinkedList();
        llist.push(20);
        llist.push(4);
        llist.push(15);
        llist.push(35);

        llist.printNthFromLast(4);
    }
}
// This code is contributed by Rajat Mishra

Output
Node no. 4 from last is 35 

Time Complexity: O(n) where n is the length of linked list. 

Auxiliary Space: O(1) using constant space.

Please refer complete article on Program for n'th node from the end of a Linked List for more details.


Next Article

Similar Reads

Java Program For Printing Nth Node From The End Of A Linked List(Duplicate)
Given a Linked List and a number n, write a function that returns the value at the n'th node from the end of the Linked List.For example, if the input is below list and n...
2 min read
Java Program For Deleting A Linked List Node At A Given Position
Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8->2->3->1->7 Output: L...
1 min read
Java Program to Delete a Node From the Beginning of the Circular Linked List
In this article, we will learn about deleting a node from the beginning of a circular linked list. Consider the linked list as shown below. Example: Input : 5->3->4-...
1 min read
Java Program to Delete a Node From the Ending of the Circular Linked List
In this article, we will learn about deleting a node from the ending of a circular linked list. Consider the linked list as shown below:  Example: Input : 5->3->4-...
1 min read
Java Program to Create a Singly Linked List and Count the Number of Nodes
Linked List is a linear data structure. Linked list elements are not stored at a contiguous location, the elements are linked using pointers. Singly Linked list is the col...
1 min read
Java Program For Finding The Middle Element Of A Given Linked List
Given a Singly linked list, find the middle of the linked list. If there are even nodes, then there would be two middle nodes, we need to print the second middle element....
3 min read
Java Program For Deleting A Node In A Linked List
We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the del...
1 min read
Java Program For Removing Middle Points From a Linked List Of Line Segments
Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a...
2 min read
Java Program For Writing A Function To Get Nth Node In A Linked List
Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->...
1 min read
Java Program For Moving Last Element To Front Of A Given Linked List
Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the funct...
1 min read