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

Joa*_*nge 18 .net c# linked-list

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

Ady*_*emp 60

无论何时您想要移动列表中的"下一个"部分,都可以快速解决以循环方式使用它的方法:

current = current.Next ?? current.List.First;
Run Code Online (Sandbox Code Playgroud)

目前的情况LinkedListNode<T>.

  • 这很光滑.我喜欢. (6认同)

Ree*_*sey 17

不是.它是一个双向链表,但不是循环链表.有关详细信息,请参阅MSDN.

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


Jac*_*cob 6

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


Art*_*hez 6

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

// This LinkedList is a doubly-Linked circular list.
internal LinkedListNode<T> head;
Run Code Online (Sandbox Code Playgroud)

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

链表节点:

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;}
}
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)