C# | Removing first occurrence of specified value from LinkedList<T>
Last Updated :
20 Jun, 2022
Remove(T) method is used to remove the first occurrence of the specified value from the LinkedList<T>. Syntax:
public bool Remove (T value);
Here, value is the value to remove from the LinkedList<T>. Return Value: This method returns True if the element containing value is successfully removed, otherwise, False. This method also returns False if value was not found in the original LinkedList<T>. Below given are some examples to understand the implementation in a better way: Example 1:
CSHARP
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(6);
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(6);
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
foreach ( int i in myList)
{
Console.WriteLine(i);
}
}
}
|
Output:
Total nodes in myList are : 6
2
4
6
6
6
8
Total nodes in myList are : 5
2
4
6
6
8
Example 2:
CSHARP
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( "H" );
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 : 5
A
B
C
D
E
Note: This method performs a linear search. Therefore, this method is an O(n) operation, where n is Count. Reference:
Space complexity: O(n) where n is size of the linked list
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__0_
Share your thoughts in the comments
Please Login to comment...