C# program to detect a cycle in Linkedlist
Here's an example of a C# program that detects a cycle in a singly linked list:
using System;
class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
class LinkedList
{
private Node head;
public void Add(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = newNode;
}
}
public bool DetectCycle()
{
if (head == null || head.Next == null)
{
return false; // No cycle in an empty or single-node linked list
}
Node slow = head;
Node fast = head;
while (fast != null && fast.Next != null)
{
slow = slow.Next;
fast = fast.Next.Next;
if (slow == fast)
{
return true; // Cycle detected
}
}
return false; // No cycle detected
}
}
class Program
{
static void Main(string[] args)
{
LinkedList list = new LinkedList();
// Creating a linked list with a cycle
Node node1 = new Node(10);
Node node2 = new Node(20);
Node node3 = new Node(30);
Node node4 = new Node(40);
Node node5 = new Node(50);
list.head = node1;
node1.Next = node2;
node2.Next = node3;
node3.Next = node4;
node4.Next = node5;
node5.Next = node2; // Creating a cycle by connecting the last node to the second node
// Detecting a cycle in the linked list
bool hasCycle = list.DetectCycle();
if (hasCycle)
{
Console.WriteLine("The linked list contains a cycle.");
}
else
{
Console.WriteLine("The linked list does not contain a cycle.");
}
}
}
This program creates a singly linked list class (LinkedList) that contains a private Node class. The Node class represents each node in the linked list and holds the data and a reference to the next node.
The LinkedList class provides two methods: Add and DetectCycle. The Add method adds a new node to the end of the linked list. The DetectCycle method uses the Floyd's Tortoise and Hare algorithm to detect a cycle in the linked list.
In the Main method, we create an instance of LinkedList and create a linked list with a cycle by connecting the last node to the second node. Then we call the DetectCycle method to check if the linked list contains a cycle. Depending on the result, we print whether the linked list contains a cycle or not.
When you run this program, it will output the following:
The linked list contains a cycle.
This indicates that a cycle was successfully detected in the linked list.