Pages

Write a Java program to check if a linked list is circular or cyclic, and how do you find if a linked list contains
loop or cycles in Java are some common linked list related data structure interview questionsasked in various Java Interviews. This is some time asked as follow-up question
of basic linked list questions like inserting element at beginning, middle and
end of linked list or finding length of linked list.
In order to solve linked list related algorithmic question in Java, you need to
be familiar with concept of singly linked list, doubly linked list and circular
linked list. Until stated specifically, most questions are based on singly
linked list. For those who are not familiar of linked list data structure, its
a collection of nodes. Each node contains two parts data and address, where
address part points to another node in linked list. Last node of linked list,
often referred as tail points to null. Also a singly list can only move in one
direction, towards end. Now, let's come back to this question. Good thing about
this question is that, it can also be solved by using two pointer approach
discussed in How to find middle element of linked list
in single pass. If a linked list contains a loop or cycle it is
known as circular or cyclic linked list. As I said we can use two pointer
approach to check if a linked list is circular or not.

Algorithm to find if linked list contains
loops or cycles

Two pointers, fast and slow is used
while iterating over linked list. Fast pointer moves two nodes in each
iteration, while slow pointer moves to one node. If linked list contains loop
or cycle than both fast and slow pointer will meet at some point during
iteration. If they don't meet and fast or slow will point to null, then linked
list is not cyclic and it doesn't contain any loop. Here is the exact algorithm

1) Use two pointers fast and slow

2) Move fast two nodes and slow one node in each iteration

3) If fast and slow meet then linked list contains cycle

4) if fast points to null or fast.next points to null then linked list is
not cyclic

Next section contains Java program to check if linked list contains loop
or cycle, which is exact implementation of above algorithm. This algorithm is
also known as Floyd’s cycle finding algorithm
and popularly known as tortoise and hare algorithm to find cycles in linked
list.

Java program to check if linked list is circular or not.

This Java program uses LinkedList(not java.util.LinkedList) and Node class from
previous example of Linked List, with modification of adding toString() methodand appendToTail() method.
Also, isCyclic() method of linked list is used to implement logic to
find if linked list contains cycle or not. Subsequently isCyclic() returns true if linked
list is cyclic otherwise it return false.

Testing linked list for cycle or loop

In this section we will test linked list using Java main method with two
linked list, one contains cycle and other is not cyclic. You can evenwrite JUnit test cases for isCyclic() method to
test different linked list with circles and loops at different positions. Here
is first test where linked list does not contain any cycle.

Let me show you an interesting point here, in case you have not noticed already. This is also asked in interviews as,
do you see anything suspicious? toString() method of LinkedList class is
not checking for cycles or loop and it will throwException in thread "main"
java.lang.OutOfMemoryError: Java heap space, if you try to print a
linked list with cycles. Now, if you are really lucky then they may ask you to
find start of loop in linked list. That's exercise for you, but let me give you
a hint, look at below diagram of a linked list which contains cycle, red
element is the start of cycle. What is special about it? If you look closely,
you can see that it's the only node in whole linked list which is next node of
other two pointers.

@Anonymous, No, that's not correct, because if fast is null means linked list is not cyclic. But original code is also not correct and will throw NullPointerException if fast is null. Instead of just checking while(fast.next != null), it should check while(fast != null && fast.next != null), that way code will prevent NullPointerException. I think author, just missed this condition.

Javin, Good post and helps many interviewees.I think, a (fast == null) check is required as also pointed by @Anonymous. Otherwise, the next condition check at beginning of while loop will throw NPE if fast becomes null

I was asked this ques on linked list..Remove the current node from the list. Lets say there is a linked list as belowA1->A2->A3->A4->A5the pointer is at A3. You have to delete the node A3 and you dont have the pointer to A2.

I still havent got the solution for that.Little help here.. anyone ???

/** * Returns the node at the start of a loop in the given circular linked * list. A circular list is one in which a node's next pointer points * to an earlier node, so as to make a loop in the linked list. For * instance: * * input: A -> B -> C -> D -> E -> C [the same C as earlier] * output: C * * * @param linkedList * list to be tested * @return the node at the start of the loop if there is a loop, null * otherwise */public static IntegerNode findLoopStart(LinkedList linkedList) { if (linkedList == null || linkedList.getHead() == null) { return null; }

// If slow and fast point to the same node, it means that the // linkedList contains a loop. if (slow == fast) {

slow = linkedList.getHead();

while (slow != fast) { // Keep incrementing the two pointers until they both // meet again. When this happens, both the pointers will // point to the beginning of the loop slow = slow.getNext(); // Can't be null, as we have a loop fast = fast.getNext(); // Can't be null, as we have a loop }

I was asked this ques on linked list..Remove the current node from the list. Lets say there is a linked list as belowA1->A2->A3->A4->A5the pointer is at A3. You have to delete the node A3 and you dont have the pointer to A2.

I still havent got the solution for that.Little help here.. anyone ???

Answer :-1) store value of A3 in some variable (temp). 2) copy the value of A4 to A3.3) Delete the node A4 (can do that as we can refer to A4 and A5)4) return temp

Back in the days in university a professor told me "if you have to interrupt a loop with a return statement, then you are not using the properly loop, nor the loop property"... So I took your code in order to make it match this corollary I was told by my professor. static boolean hasCycle(LinkedList linkedList){ LinkedList.Node slow = linkedList.head().next(); LinkedList.Node fast = linkedList.head().next().next(); while(fast!=null && fast.next()!=null && fast!=slow){ fast = fast.next().next(); slow = slow.next(); } return fast==slow; }

Does this solution also known as Floyd's Cycle-Finding Algorithm for detecting cycle on linked list? I was to explain this algorithm on an Interview but I didn't know that two pointer algorithm is also known as Floyd's Cycle Finding algorithm. Please suggest if my understanding is correct.