c# - 你如何获得链表中数字的索引?

标签 c# c#-4.0 c#-3.0 c#-2.0

我有一个链表构造如下:

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/

相关文章:

c# - 错误: Could not activate JNI Handle - WorkManager implementation in Xamarin

c# - 从 Redis 映射数据的有效方法

c# - 自定义验证未执行

visual-studio-2008 - Visual Studio 2008 .dll 消失问题

c# - 为什么我会收到 ReSharper 错误 "The extracted code has multiple entry points"?

c# - WPF MVVM 防止选项卡更改

c# - 使用 HtmlAgilityPack 在 C# 中读取表格

c# - 如何在C#中更改Windows窗体应用程序的主题

c#-4.0 - 如何让 FileHelpers 在每条记录上设置行号?

c# - 加载 AAC/MP3 文件 "manually"