C# | Removing all nodes from LinkedList<T>
Last Updated :
01 Feb, 2019
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:
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);
myList.Clear();
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
}
}
|
Output:
Total nodes in myList are : 5
Total nodes in myList are : 0
Example 2:
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);
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
myList.Clear();
Console.WriteLine( "Total nodes in myList are : " + myList.Count);
}
}
|
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...