Clear()
methodThe LinkedList<T>
generic class in the System.Collections.Generic
namespace provides the Clear()
method, which removes all nodes from a linked list in C#.
LinkedList<T>
in C# is implemented as a doubly-linked list with insertion and removal as operations.
The figure below illustrates how the Clear()
method works:
public void Clear ();
This function does not take any parameters.
The Clear()
function does not return a value.
Consider the following example code, where we create a linked list of strings and add the names of a few companies to it.
using System;using System.Collections.Generic;class LinkedListClear {static void Main() {string[] companies = {"Google", "Apple", "Microsoft", "Facebook"};LinkedList<string> companyList = new LinkedList<string>(companies);Console.WriteLine("LinkedList Elements - Count : {0}", companyList.Count);Print(companyList);companyList.Clear();Console.WriteLine("LinkedList Elements After Clear() - Count : {0}", companyList.Count);Print(companyList);}private static void Print(LinkedList<string> list) {foreach (var node in list) {Console.Write(node + ", ");}Console.WriteLine("\n");}}
From line 6 to line 7, we create a linked list that contains four strings - "Google", "Apple", "Microsoft", "Facebook"
.
From line 17 to line 21, we create a helper method, Print()
, to display the linked list nodes.
In line 12, we call the Clear()
method on the linked list to remove all the nodes from the list. We can see that the list’s count property is zero and no elements are displayed.
The Count
property of the list object is set to zero.
References to other objects are released, and the first
and last
pointers are set to null
.
This is an operation, where n
is the number of elements in the list.