DAA: Floyd Cycle Detection

Floyd Cycle Detection

Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list.

In the Floyd Cycle algorithm, we have two pointers that initially point at the head. The idea of this algorithm is based on Hare and Tortoise story.

In Hare and Tortoise’s story, Hare moves twice as fast as Tortoise, and whenever the hare reaches the end of the path, the tortoise reaches the middle of the track.

Idea behind the approach -

?      Keep the Hare and Tortoise at the head node of the List.

?      In start hare moves twice as fast as tortoise.

?      While moving if hare reaches the end of the link list there is no cycle present.

?      Else move Hare and Tortoise one step ahead.

?      While moving if hare and tortoise reach same node then we get a loop.

?     Else start with step 2.

Floyd Cycle Detection

Note: Here in the code implementation, the hare is the fast pointer in our LinkedList, and the tortoise is the slow pointer in the LinkedList.

C++ code:

 #include<bits/stdc++.h>
 using namespace std;
 // Structure of Linked List nodes
 struct Node
 {
     int data;
     Node* next;
 };
 Node *head = NULL;
 void insert(int value)
 {
     // Create a new node and adjusting links
     Node* temp = new Node;
     temp->data = value;
     temp->next = head;
     head = temp;
 }
  // Function to detect cycle
 bool detectCycle()
 {
     Node *slow_ptr = head;
     Node *fast_ptr = head;  
     while (fast_ptr && fast_ptr->next)
     {
         slow_ptr = slow_ptr->next;
         fast_ptr = fast_ptr->next->next;
         if (slow_ptr == fast_ptr)
            return true; // In case if cycle is present
     }
     return false; // No cycle present
 }
 // Main Method to implement Floyd cycle algorithm
 int main()
 {
     int values[]={20, 30, 40, 50, 60};
     int n=sizeof(values)/sizeof(values[0]);
     for(int i= n-1; i>=0 ;i--)
         insert(values[i]);
     // Creating a loop
     head->next->next->next->next = head->next;
     if(detectCycle())
           cout<<"Cycle found"<<endl;
     else
           cout<<"No cycle found"<<endl; 
     return 0;
 } 

C code:

 // Floyd's Cycle Detection Algorithm
 #include <stdio.h>
 #include <stdlib.h>
 // Structure to declare a new Linked List node
 typedef struct node {
     int data;
     struct node* next;
 } node;
 node* head = NULL; // Currently head points to NULL
 // Inserting a new node into the Linked List
 node* inserting_a_new_node(int data)
 {
     node* temp;
     temp = (node*)malloc(sizeof(node));
     temp->data = data;
     temp->next = head;
     head = temp;
     return head;
 }
 // Detect if a cycle is found
 int CycleDetection(node* head)
 {
     node *pointer_fast = head, *pointer_slow = head;
     while (pointer_fast && pointer_fast->next && pointer_slow) {
         pointer_slow = pointer_slow->next;
         pointer_fast = pointer_fast->next->next;
         if (pointer_slow == pointer_fast)
             return 1;
     }
     return 0;
 }
 // Using the main method
 int main()
 {
     int n = 5;
     int linkedList[50] = { 20, 30, 40, 50, 60 };
     for (int i = 0; i < n; i++) {
         head = inserting_a_new_node(linkedList[i]);
     }
     // We are manually creating a loop
     head->next->next->next = head->next;
     if (CycleDetection(head))
         printf("Cycle is found!\n");
     else
         printf("Cycle is not found\n");
     return 0;
 } 

Java code:

 class LinkedList {
     Node head = null;
     // Linked list Node
     class Node {
         int data;
         Node next;
         Node(int val)
         {
             data = val;
             next = null;
         }
     }
     // Function to insert a node in Linked List
     public void
     insert(int val)
     {
         Node temp = new Node(val);
         temp.next = head;
         head = temp;
     }
     // Function to detect a cycle in Linked List
     boolean detectCycle()
     {
         Node slow_ptr = head;
         Node fast_ptr = head;
         while (fast_ptr != null && fast_ptr.next != null) {
             slow_ptr = slow_ptr.next;
             fast_ptr = fast_ptr.next.next;
             if (slow_ptr == fast_ptr) {
                 return true;
             }
         }
         return false;
     }
     // Main method
 public
     static void main(String args[])
     {
         LinkedList list = new LinkedList();
         int values[] = { 10, 20, 30, 40 };
         int n = values.length;
         for (int i = n - 1; i >= 0; i--)
             list.insert(values[i]);
         // Creating a loop
         list.head.next.next.next.next = list.head.next;
         if (list.detectCycle())
             System.out.println("Cycle found");
         else
             System.out.println("No cycle found");
     }
 } 

Python code:

 class Node:
     def __init__(self, data):
         self.data = data
         self.next = None
 class LinkedList:
     def __init__(self):
         self.head = None
     def insert(self, val):
         temp = Node(val)
         temp.next = self.head
         self.head = temp
 #Function to detect cycle in Linked List 
     def detectCycle(self):
         slow_ptr = self.head
         fast_ptr = self.head
         while(fast_ptr and fast_ptr.next):
             slow_ptr = slow_ptr.next
             fast_ptr = fast_ptr.next.next
             if slow_ptr == fast_ptr:
                 return True
         return False
 #Driver Code
 mylist = LinkedList()
 values=[20, 30, 40, 50, 60]
 n= len(values)
 for i in range(n-1,-1,-1):
     mylist.insert(values[i])
 #Creating a loop in Linked List
 mylist.head.next.next.next.next = mylist.head.next
 if mylist.detectCycle():
     print("Cycle found")
 else:
     print("No cycle found") 

Output:

Cycle Found

Related Topics

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

DAA: Interpolation Search Algorithm

Interpolation Search Algorithm There is no doubt that binary search is a great algorithm with average time complexity of log n. The feature of discarding one half of the array reduces...

4 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.