C# | Removing all nodes from LinkedList<T>

LinkedList<T>.Clear method is used to remove the all nodes from the LinkedList<T>.

Syntax:

public void Clear ();

Below given are some examples to understand the implementation in a better way:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<String> myList = new LinkedList<String>();
  
        // 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);
    }
}

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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<int> myList = new LinkedList<int>();
  
        // 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);
    }
}

chevron_right


Output:

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

Note:

  • Count is set to zero, and references to other objects from elements of the collection are also released.
  • First and Last are set to null.
  • This method is an O(n) operation, where n is Count.

Reference:



My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.