Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the index of a number in a linked list?

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?

like image 533
Smartboy Avatar asked Nov 15 '12 08:11

Smartboy


People also ask

Is there index in linked list?

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.

How do you get an element from a linked list?

Access LinkedList elements We can also access elements of the LinkedList using the iterator() and the listIterator() method.


1 Answers

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).

like image 63
Groo Avatar answered Oct 11 '22 13:10

Groo