Is the LinkedList in .NET a circular linked list?

我是研究僧i 提交于 2019-12-31 19:19:38

问题


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


回答1:


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

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.




回答2:


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>.




回答3:


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).




回答4:


No, its not. See MSDN




回答5:


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:

// 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:

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;
}


来源:https://stackoverflow.com/questions/1028274/is-the-linkedlist-in-net-a-circular-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!