Skip to main content

How to Use LinkedList in Csharp

If you're diving into data structures in C#, understanding the LinkedList is essential. It's a powerful and flexible type for managing sequential data. Unlike arrays or lists where data is stored in a linear manner, a LinkedList uses nodes connected by pointers. This unique structure gives it certain advantages for inserting and deleting elements. But how do you actually use it in your C# projects?

Let's break things down step by step so you can fully grasp the concept and start writing effective code with LinkedList.

What Is a LinkedList?

A LinkedList is a collection of elements, called nodes. Each node contains two parts: the data and a reference (or pointer) to the next node in the sequence. In C#, the System.Collections.Generic namespace offers the LinkedList<T> class, which allows you to create and manage a LinkedList for any data type.

You might wonder: what's the major difference between a LinkedList and an Array or List in C#? The key distinctions include:

  • Efficiency in Insertions/Deletions: Adding or removing elements in a LinkedList is faster as no resizing or shifting is required.
  • Sequential Access: LinkedLists don't offer direct access by index, so you'll rely on iterators.
  • Memory Overhead: Each node carries an additional reference, which means higher memory usage compared to arrays.

Both the doubly linked list (used by default in C#'s LinkedList<T>) and simpler single linked lists serve specific purposes, depending on your data and use case.

Key Properties of LinkedList in C#:

  1. Count: Returns the count of nodes currently in the LinkedList.
  2. First and Last: Provide access to the first and last nodes.
  3. Node-based Navigation: Functions such as AddBefore, AddAfter, and Remove are highly targeted.

Now that you have a basic understanding, let's dive into practical examples.

How to Use LinkedList in C#: Basic Operations

1. Creating a LinkedList

The first thing you'll do is initialize a LinkedList. Here's a simple example to get started:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Initialize LinkedList of integers
        LinkedList<int> numbers = new LinkedList<int>();
        
        // Add elements
        numbers.AddLast(1);  // Adds 1 at the end
        numbers.AddLast(2);
        numbers.AddFirst(0); // Adds 0 at the beginning
        
        // Display the list
        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Explanation:

  • AddFirst(0): Inserts 0 at the start.
  • AddLast(1) & AddLast(2): Append elements to the end of the list.
  • The foreach loop iterates over the list.

2. Accessing Nodes

You can access specific elements using methods and properties, but direct indexing is not supported:

class Program
{
    static void Main()
    {
        LinkedList<string> fruits = new LinkedList<string>();
        fruits.AddLast("Apple");
        fruits.AddLast("Banana");
        fruits.AddLast("Cherry");

        // Access the first and last nodes
        Console.WriteLine($"First: {fruits.First.Value}");
        Console.WriteLine($"Last: {fruits.Last.Value}");
    }
}

Explanation:

  • First.Value and Last.Value give access to the start and end elements.
  • Each node contains a Value property for its data.

3. Inserting Between Nodes

The AddBefore and AddAfter methods allow you to insert elements around specific nodes.

class Program
{
    static void Main()
    {
        LinkedList<int> numbers = new LinkedList<int>();
        numbers.AddLast(10);
        numbers.AddLast(20);
        numbers.AddLast(30);

        LinkedListNode<int> secondNode = numbers.Find(20);

        // Insert before and after the node containing 20
        numbers.AddBefore(secondNode, 15);
        numbers.AddAfter(secondNode, 25);

        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Explanation:

  • Find(value) locates a node with the specified value.
  • AddBefore and AddAfter manipulate elements relative to the found node.

4. Removing Items

You can remove elements using the Remove or RemoveFirst/RemoveLast methods:

class Program
{
    static void Main()
    {
        LinkedList<int> numbers = new LinkedList<int>();
        numbers.AddLast(100);
        numbers.AddLast(200);
        numbers.AddLast(300);
        
        numbers.Remove(200);  // Removes the node containing 200
        numbers.RemoveFirst(); // Removes the first node
        numbers.RemoveLast();  // Removes the last node

        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }
    }
}

Explanation:

  • Remove(value) targets specific elements.
  • RemoveFirst/RemoveLast handle the boundaries.

5. Iterating over a LinkedList

Lastly, iterating through a LinkedList is simple. You can use a foreach loop or access nodes manually:

class Program
{
    static void Main()
    {
        LinkedList<string> colors = new LinkedList<string>();
        colors.AddLast("Red");
        colors.AddLast("Blue");
        colors.AddLast("Green");

        LinkedListNode<string> current = colors.First;

        while (current != null)
        {
            Console.WriteLine(current.Value);
            current = current.Next; // Move to the next node
        }
    }
}

Explanation:

  • The Next property moves through the nodes.
  • Use this approach when you need node-level operations.

Conclusion

A LinkedList might seem intimidating at first, but it's an incredibly handy tool for specific programming scenarios, especially when frequent insertions or deletions are required. While they consume more memory compared to arrays, the trade-off in performance is worth it for several use cases. The examples above cover the essential LinkedList operations to get you started.

For more on improving your C# skills, check out Understanding C# Access Modifiers or explore C# Variables: A Comprehensive Guide. These topics will add depth to your knowledge and help you write better, more efficient code! So, why not experiment with LinkedList in your next project? Happy coding!

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...