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

后端 未结 5 400
天命终不由人
天命终不由人 2021-01-14 01:50

I have a linked list constructed as follows:

LinkedList linked = new LinkedList();
var array = new int[] { 23, 55, 64, 65 };
foreach (         


        
5条回答
  •  死守一世寂寞
    2021-01-14 02:19

    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(this LinkedList 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).

提交回复
热议问题