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 to find the index of the number 64?

+4
source share
4 answers

The only way to check an element against an element and increase the counter (β€œthe only way”, I say that other methods like LINQ should do the same inside).

A manual extension method will 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 this can easily be done using LINQ as @LB wrote (with the same time complexity).

+12
source
 int index = linked.Select((item, inx) => new { item, inx }) .First(x=> x.item == 64).inx; 
+2
source

Here is an alternative LINQ implementation that avoids creating anonymous objects and returns -1 if the item is not in the list:

 int index = linked.Select((n, i) => n == 64 ? (int?)i : null). FirstOrDefault(n => n != null) ?? -1; 

It converts a sequence of numbers into a sequence containing a match index, or null otherwise. It takes the first one, if any, otherwise converts the default value to int? at -1 .

Edit:

Here is a better (simpler and more efficient) alternative:

 int i = linked.TakeWhile(n => n != 64).Count(); 

i will either be equal to the index, or equal to linked.Count , if the value 64 not found.

+2
source

I think you should make your own function for list analysis and validation. The Find function returns only the first occurrence, and it is possible for you to have 2 or more entries of 64 in the list.

+1
source

Source: https://habr.com/ru/post/1446159/


All Articles