Is linked list contains loops or cycles

From Given a linked list, write a program to check if the linked list has loop or not.

For example
1->2->3->4->5->1

Solution:

using System;
using System.Collections.Generic;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var linkedList = new LinkedList();

            linkedList.Add(20);
            linkedList.Add(4);
            linkedList.Add(15);
            linkedList.Add(10);

            linkedList.Head.Next.Next.Next.Next = linkedList.Head;

            Console.WriteLine(LinkedList.IsLoopExist(linkedList.Head) ? "linked list contains cycles" : "linked list not contains loops or cycles");
            Console.ReadLine();
        }
    }

    class LinkedList
    {
        public Node Head;

        public class Node
        {
            public int Data;
            public Node Next;
            public Node(int d)
            {
                Data = d;
                Next = null;
            }
        }

        public void Add(int data)
        {
            var newNode = new Node(data) {Next = Head};
            Head = newNode;
        }

        public static bool IsLoopExist(Node h)
        {
            var s = new HashSet<Node>();
            while (h != null)
            {
                if (s.Contains(h))
                    return true;

                s.Add(h);
                h = h.Next;
            }
            return false;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *