Site icon

Floyd’s cycle detection algorithm to check loop in single linked list

What is cycle or loop in a single linked list ?

Let us take an example to elaborate the problem statement. We have shown the single linked list in Fig 1.

Fig 1: Single linked list having cyle

Floyd’s cycle detection algorithm to find loop in single linked list.

Step 1: Floyd’s cycle detection algorithm

Fig 2: Traverse single linked list (slow & fast pointers)

Step 2: Floyd’s cycle detection algorithm

Fig 3: Slow pointer & fast pointer traversal.

Step 3: Floyd’s cycle detection algorithm

Fig 4: Single linked list traversal

Step 4: Floyd’s cycle detection algorithm

Fig 5: Iterating linked list to find a loop / cycle

Time complexity of algorithm is O (n).

Program – Floyd’s cycle detection algorithm to find loop in single linked list

1.) DetectLoop Class:

package org.learn.Question;

public class DetectLoop {

	public static boolean isLooped(Node head) {
		if (null == head) {
			System.out.println("Single linked list is empty");
			return false;
		}

		Node slow = head;
		Node fast = head;
		while (slow != null && fast != null && fast.next != null) {

			fast = fast.next;
			if (slow == fast) {
				System.out.println("Loop exists in a single linked list");
				return true;
			}
			fast = fast.next;
			if (slow == fast) {
				System.out.println("Loop exists in a single linked list");
				return true;
			}
			slow = slow.next;
		}
		System.out.println("No loop exists in a single linked list");
		return false;
	}

	public static Node insert(Node head, int data) {
		while (head.next != null)
			head = head.next;
		head.next = new Node(data);
		return head.next;
	}
}

2.) DetechLoopClient Class:

package org.learn.Client;

import org.learn.Question.DetectLoop;
import org.learn.Question.Node;

public class DetechLoopClient {
	
	public static void main(String[] args) {
		int[] data = { 30, 35, 40, 45, 50, 55 };
		Node node30 = new Node(data[0]);
		Node node = null;
		
		for (int count = 1; count < data.length; count++) {
			node = DetectLoop.insert(node30, data[count]);
		}
		
		node.next = node30;
		node = new Node(20);
		node.next = new Node(25);
		node.next.next = node30;
		
		DetectLoop.isLooped(node);
	}
}

3.) Node Class:

package org.learn.Question;

public class Node {
	public int data;
	public Node next;

	public Node(int num) {
		this.data = num;
		this.next = null;
	}
}

Output – Floyd’s cycle detection algorithm to check loop in a single linked list

Loop found in linked list

Download Code – floyd algorighm to detect loop / cyle exists in single linked list

Exit mobile version