Click here to Skip to main content
15,899,475 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, i have this code from a YouTube video on how to Find the nth node from the end of a Linkedlist, this code is in a Node class but i created a Linkedlist class and added elements to my Linkedlist. I want to change the method declaration
Java
public Node nthToLast(Node node, int n)
in the Node class to accept a Linkedlist
Java
public Node nthToLast(Linkedist nthLinkedList, int n)
so that i can pass my Linkedlist as an argument from the Main method but when i changed the method declaration in the Node class i don't know how to assign the variables (pointers - curr and follower) to my Linkedlist head node so that it can work with the existing code structure. Please note, i know that a method of Node node cannot accept a LinkedList that's why i changed the method parameters, also the Node class and my Linkedlist class are in the same package. My Linkedlist class is showing an error on the
System.out.println(node.nthToLast(nthLinkedList, n));
so i didn't even border running it because i know it won't compile. Thanks for any help.
The Node class from the YouTube video -
public class Node {

    private int value;
    private Node next;

    public Node nthToLast(Node node, int n) {

        Node curr = node;
        Node follower = node;

        for (int i = 0; i < n; i++) {
            if (curr == null) {
                return null;
            }
            curr = curr.next;
        }

        while (curr.next != null) {
            curr = curr.next;
            follower = follower.next;
        }

        return follower;
    }

}


What I have tried:

My Main class where i declared and initialized my LinkedList and called the the nthToLast method from the Node class -
Java
<pre>public class FindNthNodeFromEndOfLinkedlist {

    public static void main(String[] args) {
        
        List nthLinkedList = new LinkedList<Integer>();
        
        nthLinkedList.add(1);
        nthLinkedList.add(2);
        nthLinkedList.add(3);
        nthLinkedList.add(4);
        nthLinkedList.add(5);
        
        int n = 4;
        
        Node node = new Node();
        System.out.println(node.nthToLast(nthLinkedList, n));
    } 
}
Posted
Updated 24-May-20 18:38pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900