How to find the nth element from the last in the linked list in Java – IT Blog
IT Blog
Boris IT Expert

How to find the nth element from the last in the linked list in Java

Boris~October 31, 2020 /Linked List

One of the common questions on the technical interview is to find the nth element from the last in the linked list in Java. To solve this problem, you should use the pointers’ technique. We should set two-pointers and set a needed distance between them. After that, we should move both of them until the front pointer comes to the null element.

How to find the nth element from the last in the Linked list. The detailed explanation.

Here are the detailed steps you have to follow:

        //Item we are looking for
        int neededItem = 2;
        //Pointer which helps in finding needed item from begin of the list
        ListNode frontPointer = head;

        //Moving pointer from beginning of the list to needed number of items
        while (counter < neededItem) {
            frontPointer = frontPointer.next;
            counter++;
        }
        //Pointer which helps in finding needed item based on referencePointer value
        ListNode backPointer = head;

        //Moving both pointers untill reference become null mean list is over
        while (frontPointer != null) {
            frontPointer = frontPointer.next;
            backPointer = backPointer.next;
        }

The detailed scheme:

The full implementation code (Java).

private void findThirdNodeFromTheEnd() {
        //You need to create linked list first
        creatingLinkedList();

        //Pointer which helps in finding needed item from begin of the list
        ListNode frontPointer = head;
        //Pointer which helps in finding needed item based on referencePointer value
        ListNode backPointer = head;
        //Item we are looking for
        int neededItem = 2;
        //Counter of the items
        int counter = 0;

        //Moving pointer from beginning of the list to needed number of items
        while (counter < neededItem) {
            frontPointer = frontPointer.next;
            counter++;
        }

        //Moving both pointers untill reference become null mean list is over
        while (frontPointer != null) {
            frontPointer = frontPointer.next;
            backPointer = backPointer.next;
        }

        Log.d("linkedList", "The item number " + neededItem + " from the end has value " + backPointer.data);
    }

In this article, you figured out the easiest way how to find the nth element from the last in the linked list java.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!