Remove(T)方法用于从LinkedList
句法:
public bool Remove (T value);
此处,值是要从LinkedList < T >中删除的值。
返回值:如果成功删除包含值的元素,则此方法返回True ,否则返回False 。如果在原始LinkedList < T >中找不到值,则此方法还返回False。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to remove the first
// occurrence of the specified
// value from LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a LinkedList of Integers
LinkedList myList = new LinkedList();
// Adding nodes in LinkedList
myList.AddLast(2);
myList.AddLast(4);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(6);
myList.AddLast(8);
// To get the count of nodes in LinkedList
// before removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
// Removing the first occurrence of
// the specified value from LinkedList
myList.Remove(6);
// To get the count of nodes in LinkedList
// after removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(int i in myList)
{
Console.WriteLine(i);
}
}
}
输出:
Total nodes in myList are : 6
2
4
6
6
6
8
Total nodes in myList are : 5
2
4
6
6
8
范例2:
// C# code to remove the first
// occurrence of the specified
// value from LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a LinkedList of Strings
LinkedList myList = new LinkedList();
// Adding nodes in LinkedList
myList.AddLast("A");
myList.AddLast("B");
myList.AddLast("C");
myList.AddLast("D");
myList.AddLast("E");
// To get the count of nodes in LinkedList
// before removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(string str in myList)
{
Console.WriteLine(str);
}
// Removing the first occurrence of
// the specified value from LinkedList
// As "H" is not in LinkedList, so
// there will be no change in the LinkedList
myList.Remove("H");
// To get the count of nodes in LinkedList
// after removing all the nodes
Console.WriteLine("Total nodes in myList are : " + myList.Count);
// Displaying the nodes in LinkedList
foreach(string str in myList)
{
Console.WriteLine(str);
}
}
}
输出:
Total nodes in myList are : 5
A
B
C
D
E
Total nodes in myList are : 5
A
B
C
D
E
注意:此方法执行线性搜索。因此,此方法是O(n)运算,其中n是Count 。
参考:
https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.remove?view=netframework-4.7.2#System_Collections_Generic_LinkedList_1_Remove__0_