Advertisement



< Prev
Next >



C# LinkedList<T> Class





LinkedList<T> is a generic collection class which implements a double-ended linked list and used to store a collection of single type of values. The LinkedList<T> encapsulates these values within nodes of type LinkedListNode<T>, where each node contains a link to the previous or the next value in the list.

LinkedList<T> is defined within System.Collections.Generic namespace and it implements ICollection, ICollection<T>, IEnumerable, IEnumerable<T>, ISerializable, and IDeserializationCallback interfaces.


Important features of LinkedList<T>







Some constructors of LinkedList<T>:


Constructors Description
LinkedList<T>()
This constructor of List<T> creates an empty LinkedList<T> and has the default initial capacity.

The capacity of an LinkedList<T> is the number of elements it can hold, as the new elements are added to the LinkedList<T>, its capacity is automatically increased.

LinkedList<T>(IEnumerable<T>)
This constructor creates an List<T> initialized with the elements of an IEnumerable<T> collection.






Properties of List<T>


Properties Description
Count
This property gives total number of elements in an List<T>.

First
This property returns the first node of the LinkedList<T>.

Remember, each node in LinkedList<T> is of type LinkedListNode<T>.

Last
This property returns the last node of the LinkedList<T>.






Properties of LinkedListNode<T>


Properties Description
Next
This property gets the next node in the LinkedList<T>.

Previous
This property gets the previous node in the LinkedList<T>.

List
This property gets the LinkedList<T> that the LinkedListNode<T> belongs to..

Value
This property gets the value contained in the node.






Some commonly used methods of LinkedList<T> class


Methods Description
void AddFirst(T value)
Adds a new node containing the specified value at the start in the LinkedList<T>.

void AddFirst(LinkedListNode<T> newnode)
Adds a new node at the start of the LinkedList<T>.

void AddLast(T value)
Adds a new node containing the specified value to the end of the LinkedList<T>.

void AddLast(LinkedListNode<T> newnode)
Adds a new node to the end of the LinkedList<T>.

void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newnode)
Adds a new node before the specified node in the LinkedList<T>.

void AddBefore(LinkedListNode<T> node, T value)
Adds a new node containing the specified value before the specified node in the LinkedList<T>.

void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newnode)
Adds a new node after the specified node in the LinkedList<T>.

void AddAfter(LinkedListNode<T> node, T value)
Adds a new node containing the specified value after the specified node in the LinkedList<T>.

bool Contains(T value)
This method checks if LinkedList<T> contains a specific value.

void Clear()
This method removes all the elements from the LinkedList<T>.

LinkedListNode<T> Find(T node)
Finds the specified node from the LinkedList<T>.

LinkedListNode<T> Find(LinkedListNode<T> node)
Finds the specified node that contains the specified value in the LinkedList<T>.

void Remove(LinkedListNode<T> node)
Removes the specified node from the LinkedList<T>.

bool Remove(T value)
Removes the first occurrence of a specified value from the LinkedList<T>.

void RemoveFirst()
Removes the first node from the LinkedList<T>.

void RemoveLast()
Removes the last node from the LinkedList<T>.

LinkedList<T>.Enumerator GetEnumerator()
This method returns to enumerate the entire LinkedList<T>.




Advertisement




Example of LinkedList<T>


In this program, we have created a LinkedList<T> to hold <String> objects and we will add/remove some elements from this list by calling the following methods:

using System;
using System.Collections.Generic;

class LinkedListEx
{
public static void Main(String[] ar)
{
	//Creating a LinkedList<T> of type String i.e. LinkedList<String>
	//To hold values of type String
	LinkedList<String> link= new LinkedList<String>();


	//Calling the AddFirst(T value) method
	link.AddFirst("B");
	link.AddFirst("3");
	link.AddFirst("B");


	//Calling the AddLast(T value) method
	link.AddLast("2");
	link.AddLast("c");
	

	//Calling the AddFirst(T value) method
	link.AddFirst("1");


	Console.WriteLine("LinkedList<String> after adding objects: ");
	foreach(String element in link)
		Console.WriteLine(element);


	//Calling the RemoveFirst() method
	link.RemoveFirst();
	
	//Printing  the updated LinkedList<String>
	Console.WriteLine("After removing first element, LinkedList<String> is: ");
	foreach(String element in link)
		Console.WriteLine(element);



	//Calling the RemoveFirst() method 
	link.RemoveLast();

	//Printing the updated LinkedList<String>
	Console.WriteLine("After removing Last element, LinkedList<String> is: ");
	foreach(String element in link)
		Console.WriteLine(element);

 

	//Calling the Remove(T value) method
	link.Remove("2");	
	
	//Printing the updated LinkedList<String>
	Console.WriteLine("After removing 2, from LinkedList<String> is: ");
	foreach(String element in link)
		Console.WriteLine(element);	
}
}


Output is - :


LinkedList<String> after adding objects:
1
B
3
B
2
c
After removing first element, LinkedList<String> is:
B
3
B
2
c
After removing Last element, LinkedList<String> is:
B
3
B
2
After removing 2, from LinkedList<String> is:
B
3
B





Traversing LinkedList<T> backwards


In this program, we have created a LinkedList<T> to hold <String> objects and we will first iterate through its elements from its start to the end and then backwards as well. For this, we will use the properties of LinkedListNode<T> with the properties of LinkedList<T>

//C# Traversing LinkedList<T> forward and backward


using System;
using System.Collections.Generic;

class LinkedListEx
{
public static void Main(String[] ar)
{
	//Creating a LinkedList<T> of type String i.e. LinkedList<String>
	//To hold values of type String
	LinkedList<String> link= new LinkedList<String>();


	//Calling the AddFirst(T value) method
	link.AddFirst("B");
	link.AddFirst("3");
	link.AddFirst("B");


	//Calling the AddLast(T value) method
	link.AddLast("2");
	link.AddLast("c");
	

	//Calling the AddFirst(T value) method
	link.AddFirst("1");


	Console.WriteLine("LinkedList<String> after adding objects: ");
	foreach(String element in link)
		Console.WriteLine(element);

	LinkedListNode<String> node;

	//Displaying the list backward from last to first.
	//by using the property 'Last' of LinkedList<T>
	//and, by using the property 'Previous' of LinkedListNode<T>
	//And, display the value of each node by using property 'Value' of LinkedListNode<T>
	Console.Write("Traversing LinkedList backwards: ");
	for(node = link.Last; node != null; node = node.Previous)
		Console.WriteLine(node.Value + " ");
}
}


Output is - :


LinkedList after adding objects:
1
B
3
B
2
c
Traversing LinkedList backwards: c
2
B
3
B
1





Creating a new LinkedList<T> from an existing LinkedList<T>


In this program, we will create a LinkedList<T> that holds int values, and because C# has a unified type system, so any primitive values like int, char, float, etc are implicitly boxed into an Object reference.

We will create and initialize a new LinkedList<T> using the contents of an existing LinkedList<T>.

//Creating a new LinkedList<T> from an existing LinkedList<T>
  
using System;
using System.Collections.Generic;

class LinkedListEx
{
public static void Main(String[] ar)
{
	//Creating a LinkedList<T> of type String i.e. LinkedList<int>
	//To hold values of type int
	LinkedList<int> link= new LinkedList<int>();


	//Calling the AddFirst(T value) method
	link.AddFirst(4);
	link.AddFirst(12);
	link.AddFirst(2);


	//Calling the AddLast(T value) method
	link.AddLast(90);
	link.AddLast(77);
	

	//Calling the AddFirst(T value) method
	link.AddFirst(21);


	Console.WriteLine("First LinkedList<int> after adding objects: ");
	foreach(int element in link)
		Console.WriteLine(element);
 

	//Creating a new LinkedList<int> from the existing LinkedList<int>
	LinkedList<int> link2 = new LinkedList<int>(link);


	//Printing the new LinkedList<int>
	Console.WriteLine("Second LinkedList<int> created from the first existing LinkedList<int>");
	foreach(int element in link)
		Console.WriteLine(element);	
}
}



Output is - :


First LinkedList<String> after adding objects:
21
2
12
4
90
77
Second LinkedList<int> created from the first existing LinkedList<int>
21
2
12
4
90
77





Adding LinkedListNode<T> nodes to the LinkedList<T>.


In this program, we have created a LinkedList<T> by adding nodes of type LinkedListNode<T> by calling the following LinkedListNode<T> specific methods:

//C# Adding LinkedListNode<T> nodes to the LinkedList<T>.
 
 
using System;
using System.Collections.Generic;

class LinkedListEx
{
public static void Main(String[] ar)
{
	//Creating a LinkedList<T> of type String i.e. LinkedList<char>
	//To hold values of type String
	LinkedList<char> link= new LinkedList<char>();

	//Creating LinkedListNode<T> nodes of type char i.e. LinkedListNode<char>
	LinkedListNode<char> node1 = new LinkedListNode<char>('R');
	LinkedListNode<char> node2= new LinkedListNode<char>('A');
	LinkedListNode<char> node3 = new LinkedListNode<char>('X');
	LinkedListNode<char> node4 = new LinkedListNode<char>('s');
	LinkedListNode<char> node5 = new LinkedListNode<char>('e');
	LinkedListNode<char> node6 = new LinkedListNode<char>('B');

	//Calling the AddFirst(LinkedListNode<T> node) method
	link.AddFirst(node1);
	link.AddFirst(node2);
	link.AddFirst(node3);


	//Calling the AddLast(LinkedListNode<T> node) method
	link.AddLast(node4);
	link.AddLast(node5);
	

	//Calling the AddFirst(LinkedListNode<T> node) method
	link.AddFirst(node6);


	Console.WriteLine("LinkedList<char> after adding objects: ");
	foreach(char element in link)
		Console.WriteLine(element);

	
	//Creating new LinkedListNode<T> nodes of type char i.e. LinkedListNode<char>
	LinkedListNode<char> node7 = new LinkedListNode<char>('D');
	LinkedListNode<char> node8 = new LinkedListNode<char>('H');

	//Calling the AddBefore(LinkedListNode<T> node) method
	link.AddBefore(node3, node7);
	
	//Printing  the updated LinkedList<char>
	Console.WriteLine("After adding a new node('D') before node3('X'), LinkedList<char> is: ");
	foreach(char element in link)
		Console.WriteLine(element);



	//Calling the AddAfter(LinkedListNode<T> node) method
	link.AddAfter(node1, node8);
	
	//Printing  the updated LinkedList<char>
	Console.WriteLine("After adding a new node('H') after node1('R'), LinkedList<char> is: ");
	foreach(char element in link)
		Console.WriteLine(element);
		
		
	//Calling the Remove(T value) method
	link.Remove('H');


	//Calling the Remove(LinkedListNode&;t;T>) method
	link.Remove(node2);

	
	//Printing the updated LinkedList<char>
	Console.WriteLine("After removing the node with value 'H' and node2('A'), LinkedList<char> is: ");
	foreach(char element in link)
}
}


Output is - :


LinkedList<char> after adding objects:
B
X
A
R
s
e
After adding a new node('D') before node3('X'), LinkedList<char> is:
B
D
X
A
R
s
e
After adding a new node('H') after node1('R'), LinkedList<char> is:
B
D
X
A
R
H
s
e
After removing the node with value 'H' and node2('A'), LinkedList<char> is:
B
D
X
R
s
e

As you can see the code that we have called the following variants of Remove() method to remove the existing nodes of type LinkedListNode<T> , each node in LinkedList<T> is of type LinkedListNode<T> and can be removed by even calling the simple by calling the LinkedListNode<T> specific and non LinkedListNode<T> specific methods:



Cannot add an existing node to the LinkedList<T>.


Adding the existing node of type LinkedListNode<T> to the LinkedList<T> throws an exception of type System.InvalidOperationException:.

using System;
using System.Collections.Generic;

class LinkedListEx
{
public static void Main(String[] ar)
{
	//Creating a LinkedList<T> of type String i.e. LinkedList<String>
	//To hold values of type String
	LinkedList<char> link= new LinkedList<char>();

	//Creating LinkedListNode<T> nodes of type char i.e. LinkedListNode<char>
	LinkedListNode<char> node1 = new LinkedListNode<char>('R');
	LinkedListNode<char> node2= new LinkedListNode<char>('A');
	LinkedListNode<char> node3 = new LinkedListNode<char>('X');
	LinkedListNode<char> node4 = new LinkedListNode<char>('s');
	LinkedListNode<char> node5 = new LinkedListNode<char>('e');
	LinkedListNode<char> node6 = new LinkedListNode<char>('B');

	//Calling the AddFirst(LinkedListNode<T> node) method
	link.AddFirst(node1);
	link.AddFirst(node2);
	link.AddFirst(node3);


	//Calling the AddLast(LinkedListNode<T> node) method
	link.AddLast(node4);
	link.AddLast(node5);
	link.AddFirst(node6);


	Console.WriteLine("LinkedList<char> after adding objects: ");
	foreach(char element in link)
		Console.WriteLine(element);

	
	//Creating new LinkedListNode<T> node of type char i.e. LinkedListNode<char>
	//Which already exists in our LinkedList<char>
	LinkedListNode<char> node7 = new LinkedListNode<char>('A');

	
	//Calling the AddLast(LinkedListNode<T> node) method
	//To add the existing node to the LinkedList<char>
	link.AddLast(node6);
}
}


Output is - :


LinkedList<char> after adding objects:
B
X
A
R
s
e

Unhandled Exception: System.InvalidOperationException: The LinkedList node already belongs to a LinkedList.
   at System.Collections.Generic.LinkedList`1.ValidateNewNode(LinkedListNode`1 node)
   at System.Collections.Generic.LinkedList`1.AddLast(LinkedListNode`1 node)
   at LinkedListEx.Main(String[] ar)

The InvalidOperationException exception is also thrown if node is part of another existing list.



Please share this article -





< Prev
Next >
< C# Generic Queue
C# Generic List >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement