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 end of the Linked List
In C#, you can remove the last node from a LinkedList using the RemoveLast() method. This method removes and returns the last node in the linked list, making it an efficient way to delete the tail element.
Syntax
Following is the syntax for removing the last node from a LinkedList −
linkedList.RemoveLast();
The RemoveLast() method removes the last node and has no return value. If the list is empty, it throws an InvalidOperationException.
How It Works
The LinkedList<T> class maintains references to both the first and last nodes. When RemoveLast() is called, it directly accesses the last node and removes it by updating the previous node's next reference and the list's last node reference.
Example
The following example demonstrates how to remove the last node from a LinkedList −
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string[] employees = {"Patrick", "Robert", "John", "Jacob", "Jamie"};
LinkedList<string> list = new LinkedList<string>(employees);
Console.WriteLine("Original LinkedList:");
foreach (var emp in list) {
Console.WriteLine(emp);
}
// removing last node
list.RemoveLast();
Console.WriteLine("\nLinkedList after removing last node:");
foreach (var emp in list) {
Console.WriteLine(emp);
}
}
}
The output of the above code is −
Original LinkedList: Patrick Robert John Jacob Jamie LinkedList after removing last node: Patrick Robert John Jacob
Handling Empty LinkedList
When working with RemoveLast(), it's important to check if the LinkedList is empty to avoid exceptions −
using System;
using System.Collections.Generic;
class SafeRemovalDemo {
static void Main() {
LinkedList<int> numbers = new LinkedList<int>();
numbers.AddLast(10);
numbers.AddLast(20);
Console.WriteLine("Count before removals: " + numbers.Count);
// Safe removal using Count check
while (numbers.Count > 0) {
Console.WriteLine("Removing: " + numbers.Last.Value);
numbers.RemoveLast();
Console.WriteLine("Count: " + numbers.Count);
}
// This would throw an exception
// numbers.RemoveLast(); // InvalidOperationException
Console.WriteLine("LinkedList is now empty.");
}
}
The output of the above code is −
Count before removals: 2 Removing: 20 Count: 1 Removing: 10 Count: 0 LinkedList is now empty.
Conclusion
The RemoveLast() method provides an efficient way to remove the last node from a LinkedList in C#. Always check if the list is empty before calling this method to avoid InvalidOperationException. This operation has O(1) time complexity since LinkedList maintains a direct reference to the last node.
