Linked List Locate From End

public class LinkedListLocateFromEnd {

    // Static inner class representing a node
    public static class Node {

        int data;
        Node next;

        public Node(int data) {
            this.data = data;
            this.next = null;
        }
    }

    // Print the entire linked list
    public static void printList(Node head) {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " → ");
            current = current.next;
        }
        System.out.println("null");
    }

    // Return the value of the nth node from the end
    public static int findNthFromEnd(Node head, int n) {
        if (head == null) {
            System.out.println("Empty list.");
            return -1;
        }
        if (n <= 0) {
            System.out.println("Invalid n: must be > 0.");
            return -1;
        }

        Node fast = head;
        Node slow = head;

        // Move fast pointer n steps ahead
        for (int i = 0; i < n; i++) {
            if (fast == null) {
                System.out.println("n is larger than the length of the list.");
                return -1;
            }
            fast = fast.next;
        }

        // Move both pointers until fast reaches the end
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        return slow.data;
    }

    public static void main(String[] args) {
        // Build linked list: 10 → 20 → 30 → 40 → 50 → null
        Node head = new Node(10);
        head.next = new Node(20);
        head.next.next = new Node(30);
        head.next.next.next = new Node(40);
        head.next.next.next.next = new Node(50);

        System.out.println("Linked List:");
        printList(head);

        int n = 4;
        int result = findNthFromEnd(head, n);
        System.out.println("The " + n + "th node from the end is: " + result);
    }
}

 

Scroll to Top