你如何得到一个数字的索引链表? [英] 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);
}
如何找到数64的指数?
How do I find the index of the number 64?
推荐答案
的唯一方法是通过元素检查元素,并增加一个计数器(唯一出路,我是说其他的方法,比如LINQ需要。做内部同样的事情)
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;
}
}
但它可以很容易地使用LINQ作为<一个完成HREF =http://stackoverflow.com/a/13393641/69809> @LB写道(产生相同的时间复杂度)。
But it can easily be done using LINQ as @L.B wrote (yielding the same time complexity).
这篇关于你如何得到一个数字的索引链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文