Removing all nodes from LinkedList in C#



To remove all nodes from LinkedList, the code is as follows −

Example

 Live Demo

using System; using System.Collections.Generic; public class Demo {    public static void Main() {       int [] num = {10, 20, 30, 40, 50};       LinkedList<int> list = new LinkedList<int>(num);       Console.WriteLine("LinkedList nodes...");       foreach (var n in list) {          Console.WriteLine(n);       }       list.Clear();       Console.WriteLine("LinkedList is empty now!");       foreach (var n in list) {          Console.WriteLine(n);       }    } }

Output

This will produce the following output −

LinkedList nodes... 10 20 30 40 50 LinkedList is empty now!

Example

Let us see another example −

 Live Demo

using System; using System.Collections.Generic; public class Demo {    public static void Main(){       LinkedList<String> list = new LinkedList<String>();       list.AddLast("A");       list.AddLast("B");       list.AddLast("C");       list.AddLast("D");       list.AddLast("E");       list.AddLast("F");       list.AddLast("G");       list.AddLast("H");       list.AddLast("I");       list.AddLast("J");       Console.WriteLine("Count of nodes = " + list.Count);       list.Clear();       Console.WriteLine("Count of nodes (updated) = " + list.Count);    } }

Output

This will produce the following output −

Count of nodes = 10 Count of nodes (updated) = 0
Updated on: 2019-12-04T05:58:13+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements