Working with C#'s `LinkedList` Class: Efficiently Managing Ordered Collections

Learn how to use C#'s `LinkedList` class for efficient insertion and deletion of elements at any position. This tutorial covers adding elements, finding nodes, inserting before/after nodes, and traversing the list, highlighting the advantages of linked lists over arrays and lists in scenarios with frequent data modifications.



Working with C#'s `LinkedList` Class

The C# `LinkedList` class implements a doubly linked list. Unlike arrays or lists, linked lists allow for efficient insertion and deletion of elements at any position in the list. They are suitable for situations where frequent insertions or deletions are needed.

Key Features of `LinkedList`

  • Doubly Linked: Each node points to both the previous and next nodes.
  • Efficient Insertion/Deletion: Adding or removing elements at any position is fast (O(1) time complexity).
  • Duplicate Elements Allowed: You can have multiple instances of the same element.
  • Namespace: `System.Collections.Generic`

Adding Elements to a `LinkedList`

Elements are added using `AddFirst()` (adds to the beginning) and `AddLast()` (adds to the end):


LinkedList<string> myList = new LinkedList<string>();
myList.AddFirst("Alice"); // Add to beginning
myList.AddLast("Bob");    // Add to end

Example 1: Basic `LinkedList`


using System;
using System.Collections.Generic;

public class LinkedListExample {
    public static void Main(string[] args) {
        LinkedList<string> names = new LinkedList<string>();
        // ... (code to add names using AddFirst and AddLast, iterate, and print) ...
    }
}

Example 2: Inserting Before and After Nodes

You can insert elements before or after a specific node using `AddBefore()` and `AddAfter()`. The `Find()` method helps locate the node to insert before or after:


LinkedListNode<string> node = names.Find("Peter");
names.AddBefore(node, "John");  // Insert before "Peter"
names.AddAfter(node, "Mary");   // Insert after "Peter"