How to add an element before a node in a linked list in C#

The LinkedList<T> generic class in the System.Collections.Generic namespace provides the AddBefore() method. This method can be used to add a node before a specified node of a linked list in C#.

Syntax

public LinkedListNode<T> AddBefore (LinkedListNode<T> node, T value);
  • As input, this takes a node on a linked list and the T value. It will return a new LinkedListNode<T> that contains the passed input value, which is inserted before the passed input node.

  • It also has an overload available that takes a LinkedListNode<T> as input instead of the value T.

Things to note

  • This method is an O(1)O(1) operation.

  • LinkedList<T> accepts null as a valid reference type value.

  • LinkedList<T> allows duplicate values as well.

  • It throws an exception if the specified node is null.

  • It throws an exception if the specified node is in a different linked list.

Code

In the code below, we created a linked list of strings and added the names of a few months to it. The linked list contains three strings: January, March, and May.

We have saved the references of the linked list node, with March and May values to be used later as an input parameter to the AddBefore() method.

We have also created Print(), a helper method to display the linked list nodes.

Now we call the AddBefore() method while passing the linked list node for March, then we string the new node values on this linked list. The February string is the new node value. This adds February to the linked list before March. We can see that February and March are next to each other in the output.

We call the AddBefore() method again, while passing the linked list node for May and string April as the new node value. This adds a new node, the value April, before May.

Please note that the LinkedList<T> class is maintained internally as a doubly-linked list and AddBefore() is an O(1)O(1) operation.

using System;
using System.Collections.Generic;
class LinkedListAddBefore
{
static void Main()
{
LinkedList<string> monthList = new LinkedList<string>();
monthList.AddLast("January");
LinkedListNode<string> marchNode = monthList.AddLast("March");
LinkedListNode<string> mayNode = monthList.AddLast("May");
Console.WriteLine("LinkedList Elements");
Print(monthList);
monthList.AddBefore(marchNode, "February");
Console.WriteLine($"LinkedList Elements After AddBefore({marchNode.Value},'Feburary')");
Print(monthList);
monthList.AddBefore(mayNode, "April");
Console.WriteLine($"LinkedList Elements After AddBefore({mayNode.Value},'April')");
Print(monthList);
}
private static void Print(LinkedList<string> list)
{
foreach (var node in list)
{
Console.Write(node + ", ");
}
Console.WriteLine("\n");
}
}

Free Resources