In this article, we will learn about the LinkedList class.
C# LinkedList
We create a linked list in C# using the following syntax:
LinkedList<T> l1 = new LinkedList<T>();
<T> here denotes any datatype of which we want to create a linked list of.
Count: This property gets the number of nodes actually contained in the LinkedListFirst: This property gets the first node of the LinkedListLast: This property gets the last node of the LinkedListAddFirst(T): This method adds a new node containing the specified value at the start of the LinkedListAddLast(T): This method adds a new node containing the specified value at the end of the LinkedListContains(T): This method determines whether a value is in the LinkedListRemove(T): This method removes the first occurrence of the specified value from the LinkedListRemoveFirst(): This method removes the node at the start of the LinkedListRemoveLast(): This method removes the node at the end of the LinkedListClear(): This method removes all the nodes from the LinkedListDifferent LinkedList operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace LinkedListDemo {
class Example {
static void Main(string[] args) {
LinkedList < int > L = new LinkedList < int > ();
L.AddFirst(5); // Adds to the beginning
L.AddFirst(2);
L.AddLast(4); // Adds to the ending
L.AddLast(9);
foreach(int i in L) {
Console.Write(i + " ");
}
Console.WriteLine();
L.RemoveFirst(); // Removes from the beginning
L.RemoveLast(); // Removes from the ending
foreach(int i in L) {
Console.Write(i + " ");
}
Console.WriteLine();
Console.WriteLine(list.Contains(3)); // Checks if 3 is present in the list
Console.WriteLine(list.Contains(5)); // Checks if 5 is present in the list
Console.WriteLine(list.First.Value); // 'First' returns the first node in list
// 'Value' returns the value of the node
}
}
}
Output:
2 5 4 9 5 4 FalseTrue5In the editor below, perform the different tasks as directed.