Insert a node in singly linked list

Write a Program to insert a new node at the middle of the 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);
            Console.WriteLine("Sorted Linked List is:");
            linkedList.Print(linkedList.Head);
            linkedList.InsertInMiddle(100);
            Console.WriteLine("After inserting data into middle of Linked List is:");
            linkedList.Print(linkedList.Head);
            Console.ReadLine();
        }   
    }

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

        public void InsertInMiddle(int data)
        {
            var newNode = new Node(data);

            if (Head == null)
            {
                Head = newNode;
            }
            else
            {
                var count = (Size % 2 == 0) ? (Size / 2) : ((Size + 1) / 2);
                var temp = Head;
                Node current = null;

                for (var i = 0; i < count; i++)
                {
                    current = temp;
                    temp = temp.Next;
                }

                current.Next = newNode;
                newNode.Next = temp;
            }
            Size++;
        }

        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 *