C# .NET 中的 LinkedList 是循环链表吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1028274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:53:46  来源:igfitidea点击:

Is the LinkedList in .NET a circular linked list?

c#.netlinked-list

提问by Joan Venge

I need a circular linked list, so I am wondering if LinkedListis a circular linked list?

我需要一个循环链表,所以我想知道是否LinkedList是一个循环链表?

采纳答案by Reed Copsey

No. It is a doubly linked list, but not a circular linked list. See MSDN for details on this.

不是。它是双向链表,但不是循环链表。有关这方面的详细信息,请参阅MSDN

LinkedList<T> makes a good foundation for your own circular linked list, however. But it does have a definite First and Last property, and will not enumerate around these, which a proper circular linked list will.

然而,LinkedList<T> 为您自己的循环链表奠定了良好的基础。但它确实有一个明确的 First 和 Last 属性,并且不会围绕这些进行枚举,而适当的循环链表会。

回答by Lucas Jones

No, its not. See MSDN

不,这不对。见 MSDN

回答by Jacob

If you need a circular data structure, have a look at the C5 generic collections library. They have any collection that's imaginably useful in there, including a circular queue(which might help you).

如果您需要循环数据结构,请查看C5 泛型集合库。他们有任何可以想象的有用的集合,包括一个循环队列(这可能对你有帮助)。

回答by Ady Kemp

A quick solution to using it in a circular fashion, whenever you want to move the "next" piece in the list:

以循环方式使用它的快速解决方案,每当您想移动列表中的“下一个”部分时:

current = current.Next ?? current.List.First;

Where current is LinkedListNode<T>.

电流在哪里LinkedListNode<T>

回答by Arturo Torres Sánchez

While the public API of the LinkedList is not circular, internally it actually is. Consulting the reference source, you can see how it's implemented:

虽然 LinkedList 的公共 API 不是循环的,但实际上它在内部是循环的。查阅参考源,你可以看到它是如何实现的:

// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;

Of course, to hide the fact that it's circular, properties and methods that traverse the list make checks to prevent wrapping back to the head.

当然,为了隐藏它是循环的事实,遍历列表的属性和方法进行检查以防止返回到头部。

LinkedListNode:

链表节点:

public LinkedListNode<T> Next {
    get { return next == null || next == list.head? null: next;}
}

public LinkedListNode<T> Previous {
    get { return prev == null || this == list.head? null: prev;}
}

LinkedList.Enumerator:

LinkedList.Enumerator:

public bool MoveNext() {
    if (version != list.version) {
        throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
    }

    if (node == null) {
        index = list.Count + 1;
        return false;
    }

    ++index;
    current = node.item;   
    node = node.next;  
    if (node == list.head) {
        node = null;
    }
    return true;
}