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
Is the LinkedList in .NET a circular linked list?
提问by Joan Venge
I need a circular linked list, so I am wondering if LinkedList
is 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 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).
回答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;
}