Check if a linked list is circular

Problem: For a given linked list, check if it is a circular linked list or not.

Problem Explanation: Circular linked list is the typical linked list in which the last Node will have it’s next point to the Head of the List. For a given linked list 10->20, 20->30, 30->10, where 10, 20 and 30 are addresses of nodes,  it is a circular linked list. Hence output is true.

 

Java Implementation

public class CircularLL {
    public boolean isCircular(Node node) {
        Node first = node, second = node;

        while (first != null && first.getLink() != null && second.getLink() != null && second.getLink().getLink() != null) {
            first = first.getLink();
            second = second.getLink().getLink();
            if (first.hashCode() == second.hashCode()) {
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) {
        Node node1 = new Node(1, null);
        Node node2 = new Node(2, node1);
        Node node3 = new Node(3, node2);
        node1.setLink(node3);

        CircularLL circularLL = new CircularLL();
        System.out.println(circularLL.isCircular(node3));
    }
}

public class Node {
    private int value;
    private Node link;

    public Node(int value, Node n) {
        this.value = value;
        this.link = n;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }
}

TimeComplexity: O(n)


Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)