我有一个链表构造如下:
LinkedList<int> linked = new LinkedList<int>();
var array = new int[] { 23, 55, 64, 65 };
foreach (var item in array)
{
linked.AddLast(item);
}
如何找到数字 64 的索引?
最佳答案
唯一的方法是逐个元素检查并增加一个计数器(通过“唯一方法”,我是说像 LINQ 等其他方法需要在内部做同样的事情)。
手写的扩展方法看起来像这样:
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;
}
}
但是使用 LINQ 作为 @L.B wrote 可以很容易地完成(产生相同的时间复杂度)。
关于c# - 你如何获得链表中数字的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13393565/