C Sharp Linked List

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

C# LinkedList<T>

C# LinkedList class uses the concept of linked list. It allows us to insert and delete elements fastly. It can have duplicate elements. It is found in System.Collections.Generic namespace.

It allows us to add and remove element at before or last index.

# LinkedList<T> example

Let's see an example of generic LinkedList class that stores elements using AddLast() and AddFirst() methods and iterates elements using for-each loop.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class LinkedListExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a list of strings  
  9.         var names = new LinkedList<string>();  
  10.         names.AddLast("Sonoo Jaiswal");  
  11.         names.AddLast("Ankit");  
  12.         names.AddLast("Peter");  
  13.         names.AddLast("Irfan");  
  14.         names.AddFirst("John");//added to first index  
  15.   
  16.         // Iterate list element using foreach loop  
  17.         foreach (var name in names)  
  18.         {  
  19.             Console.WriteLine(name);  
  20.         }  
  21.     }  
  22. }  

Output:

John
Sonoo Jaiswal
Ankit
Peter
Irfan

Note: Unlike List, you cannot create LinkedList using Collection initializer.

C# LinkedList<T> example 2

Let's see another example of generic LinkedList class that stores elements before and after specific node. To get the specific node, we are calling Find() method.

 
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. public class LinkedListExample  
  5. {  
  6.     public static void Main(string[] args)  
  7.     {  
  8.         // Create a list of strings  
  9.         var names = new LinkedList<string>();  
  10.         names.AddLast("Sonoo");  
  11.         names.AddLast("Ankit");  
  12.         names.AddLast("Peter");  
  13.         names.AddLast("Irfan");  
  14.           
  15.         //insert new element before "Peter"  
  16.         LinkedListNode node=names.Find("Peter");  
  17.         names.AddBefore(node, "John");  
  18.         names.AddAfter(node, "Lucy");  
  19.   
  20.         // Iterate list element using foreach loop  
  21.         foreach (var name in names)  
  22.         {  
  23.             Console.WriteLine(name);  
  24.         }  
  25.     }  
  26. }  

Output:

Sonoo
Ankit
John
Peter
Lucy
Irfan

As you can see in the above output "John" and "Lucy" are added before and after "Peter".