I have a linked list constructed as follows:
LinkedList<int> linked = new LinkedList<int>();
var array = new int[] { 23, 55, 64, 65 };
foreach (var item in array)
{
linked.AddLast(item);
}
How do I find the index of the number 64?
It's important to mention that, unlike an array, linked lists do not have built-in indexes. This means that in order to find a specific point in the linked list, you need to start at the beginning and traverse through each node, one by one, until you find what you're looking for.
Access LinkedList elements We can also access elements of the LinkedList using the iterator() and the listIterator() method.
The only way is to check element by element and increase a counter (by "only way", I am saying that other methods like LINQ need to do the same thing internally).
A hand-written extension method would look something like this:
public static class LinkedListExt
{
public static int IndexOf<T>(this LinkedList<T> list, T item)
{
var count = 0;
for (var node = list.First; node != null; node = node.Next, count++)
{
if (item.Equals(node.Value))
return count;
}
return -1;
}
}
But it can easily be done using LINQ as @L.B wrote (yielding the same time complexity).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With