C# | Removing the specified node from the LinkedList<T>
Last Updated :
01 Feb, 2019
Remove(LinkedListNode<T>) method is used to remove the specified node from the LinkedList<T>.
Syntax:
public void Remove (System.Collections.Generic.LinkedListNode<T> node);
Here, node is the LinkedListNode<T> to remove from the LinkedList<T>.
Exceptions:
- ArgumentNullException : If the node is null.
- InvalidOperationException : If the node is not in the current LinkedList<T>.
Below given are some examples to understand the implementation in a better way:
Example 1:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList< int > myList = new LinkedList< int >();
myList.AddLast(2);
myList.AddLast(4);
myList.AddLast(6);
myList.AddLast(8);
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
foreach ( int i in myList)
{
Console.WriteLine(i);
}
myList.Remove(myList.First);
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
foreach ( int i in myList)
{
Console.WriteLine(i);
}
}
}
|
Output:
Total nodes in myList are : 4
2
4
6
8
Total nodes in myList are : 3
4
6
8
Example 2:
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
public static void Main()
{
LinkedList<String> myList = new LinkedList<String>();
myList.AddLast( "A" );
myList.AddLast( "B" );
myList.AddLast( "C" );
myList.AddLast( "D" );
myList.AddLast( "E" );
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
foreach ( string str in myList)
{
Console.WriteLine(str);
}
myList.Remove( "D" );
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
foreach ( string str in myList)
{
Console.WriteLine(str);
}
}
}
|
Output:
Total nodes in myList are : 5
A
B
C
D
E
Total nodes in myList are : 4
A
B
C
E
Note: This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1.remove?view=netframework-4.7.2#System_Collections_Generic_LinkedList_1_Remove_System_Collections_Generic_LinkedListNode__0__
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...