How to remove a node from the start of a linked list in C#
The LinkedList<T> generic class in the System.Collections.Generic namespace provides the RemoveFirst() method, which can remove a node from the start of a linked list in C#.
The
LinkedList<T>class in C# is internally implemented as a doubly-linked list, with insertion and removal as O(1) operations.
The illustration below shows how the RemoveFirst() method works for a linked list of strings.
Syntax
public void RemoveFirst ();
Parameters
This method does not take any parameters.
Return value
This method does not return anything.
Things to note
- This method is an O(1) operation.
RemoveFirstthrows anInvalidOperationExceptionif theLinkedList<T>object does not have any nodes.
Code
The code below demonstrates the use of the RemoveFirst() method.
using System;using System.Collections.Generic;class LinkedListRemover{static void Main(){LinkedList<string> monthList = new LinkedList<string>();monthList.AddLast("January");monthList.AddLast("February");monthList.AddLast("March");monthList.AddLast("April");monthList.AddLast("May");monthList.AddLast("June");Console.WriteLine("LinkedList Elements");Print(monthList);monthList.RemoveFirst();Console.WriteLine("LinkedList Elements After RemoveFirst()");Print(monthList);monthList.RemoveFirst();Console.WriteLine("LinkedList Elements After RemoveFirst()");Print(monthList);}private static void Print(LinkedList<string> list){foreach (var node in list){Console.Write(node + ", ");}Console.WriteLine("\n");}}
Explanation
-
In the code above, we create a linked list of strings and add the names of a few months. The linked list contains six strings -
"January","February","March","April","May", and"June". -
We also create a helper method,
Print(), to display the linked list nodes. -
We call the
RemoveFirst()method on the linked list and it removes the node from the start of the list. We can see that the first node,"January", is removed in the output. -
We call the
RemoveFirst()method again and print all the nodes. We can observe that the first element,"February", is also removed from the list and is not present in the output.