Sort singly linked list

Write a program to sort singly 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(2);
            linkedList.Add(3);
            linkedList.Add(9);

            linkedList.SortList(linkedList.Head);
            Console.WriteLine("Sorted Linked List is:");
            linkedList.Print(linkedList.Head);
            Console.ReadLine();
        }   
    }

    
    public class LinkedList
    {
        public Node Head;

        public void SortList(Node head)
        {
            var current = head;

            if (head == null)
            {
                return;
            }

            while (current != null)
            {
                var index = current.Next;

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

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

        public void Print(Node head)
        {
            while (head != null)
            {
                Console.WriteLine(head.Data);
                head = head.Next;
            }
        }
    }

    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 *