How is a LinkedList used in C#?
In C#, the LinkedList class represents a doubly linked list data structure, which allows common operations such as adding, removing, and searching for elements in the list. LinkedList can store a series of elements and supports insertion or deletion operations at any position.
Here are some common usages of the LinkedList class:
- Create an empty LinkedList.
LinkedList<int> linkedList = new LinkedList<int>();
- Add elements to the LinkedList.
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
- Insert elements at a specified position.
var node = linkedList.Find(2); // 查找值为2的节点
if (node != null)
{
linkedList.AddAfter(node, 4); // 在值为2的节点后插入值为4的节点
}
- Remove specified elements.
linkedList.Remove(2);
- Iterate through LinkedList:
foreach (var item in linkedList)
{
Console.WriteLine(item);
}
The LinkedList class offers a variety of methods for manipulating linked list data structures, allowing for flexible insertion, deletion, and retrieval operations as needed.