Sort Circular Linked List

Write a Program to sort the elements of the circular linked list.

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($"Circular Linked List");
            linkedList.Print();
            linkedList.Sort();
            Console.WriteLine($"After Sorting Circular Linked List");
            linkedList.Print();
            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 void Print()
        {
            Node current = Head;
            if (Head == null)
                return;

            do
            {
                Console.WriteLine(current.Data);
                current = current.Next;
            } while (current != Head);
        }

        public void Sort()
        {
            Node current = Head;
            if (Head == null)
                return;

            do
            {
                var index = current.Next;
                while (index != Head)
                {
                    if (current.Data > index.Data)
                    {
                        var temp = current.Data;
                        current.Data = index.Data;
                        index.Data = temp;
                    }
                    index = index.Next;
                }
                current = current.Next;
            } while (current.Next != Head);
        }

    }

    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 *