Open In App

C# LinkedList

Last Updated : 31 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C# a LinkedList is a linear data structure that stores elements in a non-contiguous location. The elements in a linked list are linked with each other using pointers. In other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of collection that is defined in the System.Collections.Generic namespace. It is a doubly linked list, therefore, each node points forward to the Next node and backward to the Previous node. It is a dynamic collection that grows, according to the needs of our program. It also provides fast inserting and removing elements

  • It supports enumerators for easy traversal.
  • We can remove nodes and reinsert them, either in the same list or another list, resulting in no additional objects allocated on the heap.
  • Every node in a LinkedList<T> object is of the type LinkedListNode<T>.
  • It can store duplicate elements of the same type
  • Its capacity depends on the number of elements it can hold.

Example:

C#
// C# program to Add elements to a LinkedList
using System;
using System.Collections.Generic;

class Geeks {
    static void Main()
    {
        // Create a new LinkedList of strings
        LinkedList<int> l = new LinkedList<int>();

        // Add elements to the LinkedList

        // Adds at the end
        l.AddLast(10);
        // Adds at the beginning
        l.AddFirst(20);
        // Adds at the end
        l.AddLast(30);
        // Adds at the end
        l.AddLast(40);

        // Display the elements in the LinkedList
        Console.WriteLine("Elements in the LinkedList:");
        foreach(var i in l) { 
          Console.WriteLine(i); 
        }
    }
}

Output
Elements in the LinkedList:
20
10
30
40

Hierarchy of LinkedList

CSharp-LinkedList

Interfaces

In C#, the LinkedList<T> class implements the interfaces which are listed below:

  • ICollection<T>
  • IEnumerable<T>
  • IEnumerable
  • ICollection

Constructors

In C#, the LinkedList<T> class has 3 constructors which are used to create a LinkedList which are as follows:

  • LinkedList(): This constructor is used to create an instance of the LinkedList class that is empty.
  • LinkedList(IEnumerable): This constructor is used to create an instance of the LinkedList class that contains elements copied from the specified IEnumerable and has sufficient capacity to accommodate the number of elements copied.
  • LinkedList(SerializationInfo, StreamingContext): This constructor is used to create an instance of the LinkedList class that is serializable with the specified SerializationInfo and StreamingContext.

Creating a LinkedList

Let’s see how to create an LinkedList using LinkedList() constructor:

 Step 1: Include System.Collections.Generic namespace in your program with the help of “using” keyword.

using System.Collections.Generic;

Step 2: Create a LinkedList using LinkedList class

LinkedList <String> l = new LinkedList <String>();

Performing Different Operations on LinkedList

1. Adding Elements: LinkedList class provides four different methods to insert nodes and these methods are listed below:

  • AddAfter(): This method is used to add a new node or value after an existing node in the LinkedList.
  • AddBefore(): This method is used to add a new node or value before an existing node in the LinkedList.
  • AddFirst(): This method is used to add a new node or value at the start of the LinkedList.
  • AddLast(): This method is used to add a new node or value at the end of the LinkedList.

Example: This example demonstrates how to create a LinkedList<int>, adding elements to it usind AddLast() and displaying the elements using a foreach loop.

C#
// Creating and adding elements to the LinkedList
using System;
using System.Collections.Generic;

class Geeks {

    static void Main()
    {
        // Creating a linked l of integers
        LinkedList<int> l = new LinkedList<int>();

        // Adding elements to the LinkedList using AddLast()
        l.AddLast(10);
        l.AddLast(20);
        l.AddLast(30);
        l.AddLast(40);
        l.AddLast(50);

        Console.WriteLine("List of numbers:");

        // Accessing and displaying the elements using
        // foreach loop
        foreach(int num in l) { Console.WriteLine(num); }
    }
}

Output
List of numbers:
10
20
30
40
50

2. Removing Elements: LinkedList<T> class provides five different methods to remove elements and the methods are:

  • Clear(): Clear() method is used to remove all nodes from the LinkedList.
  • Remove(LinkedListNode): Remove(LinkedListNode) method is used to remove the specified node from the LinkedList.
  • Remove(T): Remove(T) method is used to remove the first occurrence of the specified value from the LinkedList.
  • RemoveFirst(): RemoveFirst() method is used to remove the node at the start of the LinkedList.
  • RemoveLast(): RemoveLast() method is used to remove the node at the end of the LinkedList.

Example:

C#
// Remove elements from the LinkedList
using System;
using System.Collections.Generic;

class Geeks {

    static void Main()
    {
        // Creating a LinkedList of integers
        LinkedList<int> l = new LinkedList<int>();

        // Adding elements to the LinkedList using AddLast()
        l.AddLast(10);
        l.AddLast(20);
        l.AddLast(30);
        l.AddLast(40);
        l.AddLast(50);
        l.AddLast(60);

        // Initial list of numbers
        Console.WriteLine("Initial List of Numbers: "
                          + string.Join(" ", l));

        // Removing the first element using
        // Remove(LinkedListNode)
        l.Remove(l.First);
        Console.WriteLine(
            "\nAfter Removing the First Element: "
            + string.Join(" ", l));

        // Removing a specific element (20) using Remove(T)
        l.Remove(20);
        Console.WriteLine("\nAfter Removing Number 20: "
                          + string.Join(" ", l));

        // Removing the first element using RemoveFirst()
        l.RemoveFirst();
        Console.WriteLine(
            "\nAfter Removing the First Element Again: "
            + string.Join(" ", l));

        // Removing the last element using RemoveLast()
        l.RemoveLast();
        Console.WriteLine(
            "\nAfter Removing the Last Element: "
            + string.Join(" ", l));

        // Clearing the entire linkedlist
        l.Clear();
        Console.WriteLine(
            "\nNumber of elements in the list after clearing: "
            + l.Count);
    }
}

Output:

Output

3. Checking the Availability of Elements in the LinkedList: LinkedList class provide Contains(T) method to check if the element is present in the LinkedList or not.

C#
// Checking the Availability of 
// Elements in the LinkedList
using System;
using System.Collections.Generic;

class Geeks {
    public static void Main(string[] args)
    {
        // Create a new LinkedList of integers
        LinkedList<int> l = new LinkedList<int>();

        // Add elements to the LinkedList using AddLast()
        l.AddLast(10);
        l.AddLast(20);
        l.AddLast(30);

        // Check if the element 20 is present in the LinkedList
        Console.WriteLine(
                "The element 20 is present in the LinkedList: "
                        + l.Contains(20));

        // Check if the element 100 is present in the LinkedList
        Console.WriteLine(
                "The element 100 is present in the LinkedList: "
                        + l.Contains(100));
    }
}

Output
The element 20 is present in the LinkedList: True
The element 100 is present in the LinkedList: False


Next Article

Similar Reads