C# LinkedList

C# LinkedList<T> is a built-in data structure provided by the .NET Framework and is part of the System.Collections.Generic namespace. It represents a doubly linked list, where each element in the list contains a reference to the next and previous elements. The T in LinkedList<T> represents the type of the elements stored in the list.

Here’s an example of how to use LinkedList<T> in C#:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Create a new LinkedList of integers
        LinkedList<int> numbers = new LinkedList<int>();

        // Add elements to the LinkedList
        numbers.AddLast(1);
        numbers.AddLast(2);
        numbers.AddLast(3);

        // Iterate over the LinkedList
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }

        // Insert an element at the beginning of the LinkedList
        numbers.AddFirst(0);

        // Remove an element from the LinkedList
        numbers.Remove(2);

        // Check if an element exists in the LinkedList
        bool containsThree = numbers.Contains(3);

        // Get the first and last elements of the LinkedList
        int firstNumber = numbers.First.Value;
        int lastNumber = numbers.Last.Value;

        Console.WriteLine("After modifications:");

        // Iterate over the modified LinkedList
        foreach (int number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Output:

1
2
3
After modifications:
0
1
3

In the example above, we create a LinkedList<int> and add some elements to it. We then iterate over the list, add an element at the beginning, remove an element, check if an element exists, and retrieve the first and last elements. Finally, we iterate over the modified list to see the changes.

LinkedList<T> provides efficient insertion and removal operations compared to other list types like List<T>, especially when dealing with large collections where frequent modifications are required. However, it has slower random access because it doesn’t provide indexed access like List<T>.