Middle Element of Linked List - Java

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;
    }
}

public class LLMid {

    public static LLNode getMid(LLNode root){
        LLNode midNode = null;
        LLNode helpingNode = null;

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

      while(helpingNode.getNext() != null && helpingNode.getNext().getNext() != null){
            helpingNode = helpingNode.getNext().getNext();
            midNode = midNode.getNext();
        }

        return midNode;
    }

    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();
        LLNode n7 = 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(n7).setValue(6);
        n7.setNext(null).setValue(7);
        LLNode mid = getMid(n1);
        System.out.println(mid.getValue());
    }
}

Output: 4

Comments

Popular posts from this blog

public vs protected vs default access modifiers - Java

Class, Reference and Object