C# Linked List Creation Guide

There are two methods for creating linked lists in C#.

  1. Class: This is the built-in linked list implementation in C#, which can be used directly. Firstly, you need to import the System.Collections.Generic namespace, and then you can create a linked list using the following code.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        LinkedList<int> linkedList = new LinkedList<int>();
        linkedList.AddLast(1);
        linkedList.AddLast(2);
        linkedList.AddLast(3);
        
        foreach (var item in linkedList)
        {
            Console.WriteLine(item);
        }
    }
}
  1. Custom linked list class: You can also implement the functionality of a linked list by creating a custom linked list class. For example, you can create a Node class and a LinkedList class to represent the nodes of the linked list and the linked list itself.
using System;

class Node
{
    public int data;
    public Node next;

    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}

class LinkedList
{
    public Node head;

    public void Add(int data)
    {
        Node newNode = new Node(data);
        if (head == null)
        {
            head = newNode;
        }
        else
        {
            Node current = head;
            while (current.next != null)
            {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    public void Display()
    {
        Node current = head;
        while (current != null)
        {
            Console.WriteLine(current.data);
            current = current.next;
        }
    }
}

class Program
{
    static void Main()
    {
        LinkedList linkedList = new LinkedList();
        linkedList.Add(1);
        linkedList.Add(2);
        linkedList.Add(3);
        
        linkedList.Display();
    }
}

You can manipulate the linked list by adding or removing nodes, regardless of the method used.

bannerAds