Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to remove all nodes of a linked list in C#

Surabhi Sharma

The Clear() method

The 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 O(1)O(1) operations.

The figure below illustrates how the Clear() method works:

Working of the clear() method

Syntax

public void Clear ();

Parameters

This function does not take any parameters.

Return value

The Clear() function does not return a value.

Code

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");     
    }
}

Explanation

  • 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.

Things to note

  • 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 O(n)O(n) operation, where n is the number of elements in the list.

RELATED TAGS

c#
communitycreator
RELATED COURSES

View all Courses

Keep Exploring