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#.
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
.
This method is an 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.
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 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");}}