Detect a Loop in Singly Linked List and Remove Loop

Floyd’s Cycle-Finding Algorithm: This is the fastest method. Traverse linked list using two pointers. Move one pointer by one and other pointer by two. If these pointers meet at some node then there is a loop. If pointers do not meet then linked list doesn’t have loop.

Even More optimized

using System;
namespace ConsoleApplication1
{
    class Program
    {

        public class LinkedListNode<T>
        {
            public LinkedListNode() { }
            public LinkedListNode(T value)
            {
                Value = value;
            }
            public T Value { get; set; }
            public LinkedListNode<T> Next { get; set; }
        }

        static void Main(string[] args)
        {
            LinkedListNode<int> Llist = new LinkedListNode<int>();
            Llist.Next = new LinkedListNode<int>(1);
            Llist.Next.Next = new LinkedListNode<int>(2);
            Llist.Next.Next.Next = new LinkedListNode<int>(3);
            Llist.Next.Next.Next.Next = new LinkedListNode<int>(4);
            Llist.Next.Next.Next.Next.Next = new LinkedListNode<int>(5);
            Llist.Next.Next.Next.Next.Next.Next = new LinkedListNode<int>(6);

            Llist.Next.Next.Next.Next.Next.Next.Next = Llist.Next.Next.Next.Next;
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.WriteLine(FloydCycleDedection(Llist).ToString());
            Console.Read();
        }

        public static bool FloydCycleDedection<T>(LinkedListNode<T> node)
        {
            LinkedListNode<T> slow = node, fast = node;
            while (slow != null && fast != null && fast.Next != null)
            {
                slow = slow.Next;
                fast = fast.Next.Next;
                if (slow == fast)
                {
                    removeLoop(node, slow, fast);
                    return true;
                }
            }
            return false;
        }

        public static void removeLoop<T>(LinkedListNode<T> node, LinkedListNode<T> slow, LinkedListNode<T> fast)
        {
            /* If loop exists */
            if (slow == fast)
            {
                slow = node;
                while (slow != fast.Next)
                {
                    slow = slow.Next;
                }
                fast.Next = null; // remove loop
            }
        }
    }
}

results matching ""

    No results matching ""