Skip to main content

Posts

Showing posts with the label Linked List

How to Find if Linked List contains Loops or Cycles in C#

In this post I will show you how to detect loop in linked list.We can find the loop in the linked list via Floyd’s Cycle-Finding Algorithm, explained here.The algorithm is pretty straightforward: We start at the beginning of the linked list with two pointers. The first pointer is incremented through each node of the list. The second pointer moves twice as fast, and skips every other node. If the linked list contains a loop, these two pointers will eventually meet at the same node, thus indicating that the linked list contains a loop. .using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public class Node { public Node Next { get; set; } public int Value { get; set; } public Node(int value) { this.Value = value; } } public class LinkedList { private Node _head; public LinkedList() { } public vo…