Circular linked list

Write a Program to create a circular linked list of n nodes and count the number of nodes.

Solution:

using System;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var linkedList = new LinkedList();
            linkedList.Add(6);
            linkedList.Add(1);
            linkedList.Add(5);
            linkedList.Add(1);
            linkedList.Add(3);
            linkedList.Add(9);
            Console.WriteLine($"Total Count: {linkedList.Count()}");
            Console.ReadLine();
        }   
    }

    
    public class LinkedList
    {
        public Node Head;
        public Node Tail;
        public void Add(int data)
        {
            Node newNode = new Node(data);
  
            if (Head == null)
            {
                Head = newNode;
                Tail = newNode;
                newNode.Next = Head;
            }
            else
            {
                Tail.Next = newNode;
                Tail = newNode;
                Tail.Next = Head;
            }
        }

        public int Count()
        {
            var count = 0;
            Node current = Head;
            do
            {
                count++;
                current = current.Next;
            } while (current != Head);

            return count;
        }

    }

    public class Node
    {
        public int Data;
        public Node Next;

        public Node(int data)
        {
            Data = data;
        }
    }
}

Leave a Reply

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