private static bool IsListHasCycle <T1>(SingleLinkedListCycle <T1> cycle) where T1 : IComparable { SingleLinkedListCycle <T1> .Element fast; var slow = fast = cycle._head; while (true) { if (fast == null || fast.Next == null) // list is null terminated { return(false); } if (fast.Next == slow) { return(true); // has a cicle } slow = slow.Next; fast = fast.Next.Next; } }
public void FindCycle() { var cycled = new SingleLinkedListCycle <int>(); cycled.AddToFront(1); cycled.AddToFront(2); cycled.AddToFront(3); cycled._head.Next.Next.Next = cycled._head; // create a cycle var isCycled = IsListHasCycle(cycled); if (isCycled) { Console.WriteLine("isCycled"); } else { Console.WriteLine("is not cycled"); } cycled = new SingleLinkedListCycle <int>(); cycled.AddToFront(1); cycled.AddToFront(2); cycled.AddToFront(3); isCycled = IsListHasCycle(cycled); if (isCycled) { Console.WriteLine("isCycled"); } else { Console.WriteLine("is not cycled"); } }