Working with C#'s LinkedList

Introduction

Welcome! In this lesson, we'll explore C#'s LinkedList<T>, a fundamental component of the .NET Collections Framework. The LinkedList<T> class provides an efficient way to implement data structures that require constant-time insertions and deletions at any point in the sequence. We'll learn how to use this class to perform operations on linked lists effectively.

Overview of C#'s LinkedList

C#'s LinkedList<T> is part of the System.Collections.Generic namespace and represents a doubly-linked list. A doubly linked list features nodes that contain references to both the previous and next nodes in the sequence, allowing for easy bidirectional traversal. This structure balances flexibility in navigation with the increased complexity and memory usage inherent in maintaining additional pointers.

Working with C#'s LinkedList

To work with LinkedList<T> in C#, we start by including the System.Collections.Generic namespace and then create an instance of LinkedList<T>:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        LinkedList<string> students = new LinkedList<string>();
    }
}

In this code, we've set up a LinkedList called students to store elements of type string. The list is currently empty, and we'll explore adding elements and performing other operations next.

Methods in LinkedList

C#'s LinkedList<T> provides several useful methods to manipulate the list:

  • AddLast(T value): Appends an element to the end of the list.
  • AddFirst(T value): Inserts an element at the beginning of the list.
  • RemoveFirst(): Removes the first element of the list.
  • Find(T value): Searches for the first occurrence of the specified value.

These methods are demonstrated in the following code:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        LinkedList<string> students = new LinkedList<string>();

        students.AddLast("John");
        students.AddFirst("Alice");
        Console.WriteLine(students.First.Value);  // prints Alice
        students.RemoveFirst();
        Console.WriteLine(students.First.Value);  // prints John
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal