📜  C#|从LinkedList删除所有节点<T>

📅  最后修改于: 2021-05-29 19:35:41             🧑  作者: Mango

LinkedList < T > .Clear方法用于从LinkedList 中删除所有节点。

句法:

public void Clear ();

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to remove all
// nodes 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);
  
        // Removing all nodes from LinkedList
        myList.Clear();
  
        // To get the count of nodes in LinkedList
        // after removing all the nodes
        Console.WriteLine("Total nodes in myList are : " + myList.Count);
    }
}

输出:

Total nodes in myList are : 5
Total nodes in myList are : 0

范例2:

// C# code to remove all
// nodes 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);
  
        // To get the count of nodes in LinkedList
        // before removing all the nodes
        Console.WriteLine("Total nodes in myList are : " + myList.Count);
  
        // Removing all nodes from LinkedList
        myList.Clear();
  
        // To get the count of nodes in LinkedList
        // after removing all the nodes
        Console.WriteLine("Total nodes in myList are : " + myList.Count);
    }
}

输出:

Total nodes in myList are : 3
Total nodes in myList are : 0

笔记:

  • Count设置为零,并且还会释放对集合元素中其他对象的引用。
  • FirstLast设置为null
  • 此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.clear?view=netframework-4.7.2