How to create Linked List in C#

Linked List a data structure which the collection of nodes where each node contains data and link to next node.

Below code show how to create a linked list:


//Node class
public class node
    {



        public int data;
        public node next;

        public node(int _data)
        {
            data = _data;
        }
 
    }


//Linked List Class
public class LinkedList
    {
        public node head;

//Inserting node into linked list
        public void Insert(int data)
        {
            node newNode = new node(data);
            if (head == null)
            {
                head = newNode;
            }
            else
            {
                node temp = head;
                while (temp.next != null)
                {
                    temp = temp.next;
                }
                temp.next = newNode;
            }
        }
//Displays all nodes data of the linked list
        public void Display()
        {
            node temp = head;
            while (temp != null)
            {
                Console.WriteLine(temp.data);
                temp = temp.next;
            }
        }

    }

//Calling in the main function
static void Main(string[] args)
        {
            LinkedList l = new LinkedList();
   
            l.Insert(1);
            l.Insert(2);
            l.Insert(3);
            l.Insert(4);
            l.Insert(4);
            l.Insert(5);
            l.Insert(9);
            l.Display();   
        }

//Output:
1
2
3
4
4
5
9
Press any key to continue . . .

This Solution is written by me and is not completely tested. Please comment if you found any alternative solutions or any enhancement to my solution.

No comments:

Post a Comment

Popular Posts