n the last element in a linked list - Java

public class NthLastLL {
    public static void main(String[] args) {
        LLNode n1 = new LLNode();
        LLNode n2 = new LLNode();
        LLNode n3 = new LLNode();
        LLNode n4 = new LLNode();
        LLNode n5 = new LLNode();
        LLNode n6 = new LLNode();

        n1.setNext(n2).setValue(1);
        n2.setNext(n3).setValue(2);
        n3.setNext(n4).setValue(3);
        n4.setNext(n5).setValue(4);
        n5.setNext(n6).setValue(5);
        n6.setNext(null).setValue(6);
        LLNode nthLLNode = nthNode(n1,2);
        System.out.println(nthLLNode.getValue());
    }

    public static LLNode nthNode(LLNode root, int nthValue){
        LLNode nthNode = null;
        LLNode helpingNode = null;

        if(root != null){
            nthNode = root;
            helpingNode = nthNode;
        }

        for (int i = 1; i <= nthValue -1; i++) {
            helpingNode =  helpingNode.getNext();
        }

        while(helpingNode.getNext() != null){
            helpingNode = helpingNode.getNext();
            nthNode = nthNode.getNext();
        }
        return nthNode;
    }
}


public class LLNode {
    private LLNode next;
    private Object value;

    public LLNode getNext() {
        return next;
    }

    public LLNode setNext(LLNode next) {
        this.next = next;
        return this;
    }

    public Object getValue() {
        return value;
    }

    public LLNode setValue(Object value) {
        this.value = value;
        return this;
    }
}

Output: 5

Comments

Popular posts from this blog

public vs protected vs default access modifiers - Java

Class, Reference and Object