Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to remove a node at the beginning of a Linked List
To remove a node at the beginning of a LinkedList in C#, use the RemoveFirst() method. This method removes the first node from the LinkedList and automatically adjusts the internal structure.
Syntax
Following is the syntax for the RemoveFirst() method −
linkedList.RemoveFirst();
This method removes the first node and does not return any value. If the LinkedList is empty, it throws an InvalidOperationException.
How It Works
When you call RemoveFirst(), the LinkedList performs the following operations −
Example
Here's a complete example demonstrating how to remove the first node from a LinkedList −
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string[] employees = {"Peter", "Robert", "John", "Jacob"};
LinkedList<string> list = new LinkedList<string>(employees);
Console.WriteLine("Original LinkedList:");
foreach (var emp in list) {
Console.WriteLine(emp);
}
// removing first node
list.RemoveFirst();
Console.WriteLine("\nLinkedList after removing first node:");
foreach (var emp in list) {
Console.WriteLine(emp);
}
Console.WriteLine($"\nTotal nodes remaining: {list.Count}");
}
}
The output of the above code is −
Original LinkedList: Peter Robert John Jacob LinkedList after removing first node: Robert John Jacob Total nodes remaining: 3
Handling Empty LinkedList
It's important to check if the LinkedList is empty before calling RemoveFirst() to avoid exceptions −
using System;
using System.Collections.Generic;
class SafeRemoval {
static void Main() {
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
Console.WriteLine($"Initial count: {numbers.Count}");
// Safe removal with checking
while (numbers.Count > 0) {
Console.WriteLine($"Removing: {numbers.First.Value}");
numbers.RemoveFirst();
Console.WriteLine($"Remaining count: {numbers.Count}");
}
// This would be safe now
if (numbers.Count > 0) {
numbers.RemoveFirst();
} else {
Console.WriteLine("LinkedList is already empty");
}
}
}
The output of the above code is −
Initial count: 2 Removing: 10 Remaining count: 1 Removing: 20 Remaining count: 0 LinkedList is already empty
Conclusion
The RemoveFirst() method in C# provides an efficient way to remove the first node from a LinkedList. Always check if the LinkedList has elements before calling this method to avoid exceptions, and remember that it automatically updates the Count property after removal.
