How to add a node to the start of a linked list in C#
The LinkedList<T> generic class in the System.Collections.Generic namespace provides the AddFirst() method, which can be used to add a node at the start of the linked list in C#.
Syntax
public System.Collections.Generic.LinkedListNode<T> AddFirst (T value);
-
The method takes the value
Tas input and returns a newLinkedListNode<T>containing the passed input value. -
The method has an overload available that takes
LinkedListNode<T>as input and adds it to the start of the list.
Things to note
-
This method is an
O(1)operation. -
LinkedList<T>accepts null as a valid reference type value. -
LinkedList<T>allows duplicate values as well. -
For an empty linked list, the new node becomes the
Firstand theLastnode.
Code
In the below code, we created a linked list of strings named monthList and added the names of the months to it. The linked list contains three strings: March, April, and May.
using System;using System.Collections.Generic;class LinkedListAddition{static void Main(){LinkedList<string> monthList = new LinkedList<string>();monthList.AddLast("March");monthList.AddLast("April");monthList.AddLast("May");Console.WriteLine("LinkedList Elements");Print(monthList);monthList.AddFirst("February");Console.WriteLine("LinkedList Elements After AddFirst('February')");Print(monthList);monthList.AddFirst("January");Console.WriteLine("LinkedList Elements After AddFirst('January')");Print(monthList);}private static void Print(LinkedList<string> list){foreach (var node in list){Console.Write(node + ", ");}Console.WriteLine("\n");}}
Explanation
We call the AddFirst() method by passing February as the argument on this linked list. We can see that the first node is shown as February in the output.
We again call the AddFirst() method by passing January as the argument. We can see that the first node is shown as January in the output.
We created a helper method, Print(), to display the linked list nodes.
The
LinkedList<T>class is maintained internally as a doubly-linked list, andAddFirst()is anO(1)operation.