The LinkedList<T>
generic class in the System.Collections.Generic
namespace provides the RemoveLast()
method, which can remove the last node or the node at the end of the linked list.
public void RemoveLast ();
This method is an O(1) operation.
It throws an InvalidOperationException
if the LinkedList<T>
does not have any nodes.
In the example below, we have created a linked list monthList
of strings and added the names of the first few months to it.
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.RemoveLast();Console.WriteLine("LinkedList Elements After RemoveLast()");Print(monthList);monthList.RemoveLast();Console.WriteLine("LinkedList Elements After RemoveLast()");Print(monthList);}private static void Print(LinkedList<string> list){foreach (var node in list){Console.Write(node + ", ");}Console.WriteLine("\n");}}
The linked list contains six strings: " January, February, March, April, May
, and June"
.
We created a helper method, Print()
, to display the linked list nodes.
The RemoveLast()
method on this linked list removes the node from the end of the list. We can see that the last node, June, is released in the output.
We call the RemoveLast()
method again and print
the list’s nodes. We can observe that the last element, May, is also removed from the list and is not present in the output.
Please note that the
LinkedList<T>
class is maintained internally as a doubly-linked list, andRemoveLast()
is an O(1) operation.
The program prints the output and exits.