Is the LinkedList in .NET a circular linked list?

后端 未结 5 1494
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 06:56

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

5条回答
  •  萌比男神i
    2021-02-05 07:23

    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 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 Next {
        get { return next == null || next == list.head? null: next;}
    }
    
    public LinkedListNode 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;
    }
    

提交回复
热议问题