The LinkedList<T>
class in C# is a versatile doubly-linked list implementation. It offers efficient insertion and deletion operations, making it ideal for scenarios where frequent modifications are required.
A LinkedList consists of nodes, each containing data and references to the previous and next nodes. This structure allows for quick insertions and removals without shifting elements, unlike arrays or Lists.
Here's how to create and manipulate a LinkedList:
using System;
using System.Collections.Generic;
LinkedList<string> fruits = new LinkedList<string>();
// Adding elements
fruits.AddLast("Apple");
fruits.AddFirst("Banana");
fruits.AddLast("Cherry");
// Inserting an element
LinkedListNode<string> bananaNode = fruits.Find("Banana");
fruits.AddAfter(bananaNode, "Date");
// Removing an element
fruits.Remove("Cherry");
// Traversing the list
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Operation | Method | Description |
---|---|---|
Add to start | AddFirst() |
Inserts an element at the beginning |
Add to end | AddLast() |
Appends an element to the end |
Insert after | AddAfter() |
Inserts an element after a specified node |
Insert before | AddBefore() |
Inserts an element before a specified node |
Remove | Remove() |
Removes the first occurrence of a value |
Find | Find() |
Locates the first node with the specified value |
While LinkedList excels in insertion and deletion, it has some limitations:
Choose LinkedList when:
Opt for List when:
LinkedList can be used to implement other data structures efficiently. Here's an example of a simple queue implementation:
public class SimpleQueue<T>
{
private LinkedList<T> list = new LinkedList<T>();
public void Enqueue(T item)
{
list.AddLast(item);
}
public T Dequeue()
{
if (list.Count == 0)
throw new InvalidOperationException("Queue is empty");
T item = list.First.Value;
list.RemoveFirst();
return item;
}
public int Count => list.Count;
}
This implementation leverages LinkedList's efficient AddLast()
and RemoveFirst()
operations to create a performant queue structure.
By understanding the strengths and limitations of LinkedList, you can make informed decisions about when to use this powerful data structure in your C# applications.