Creating a circularly linked list in C#?

后端 未结 10 1166
独厮守ぢ
独厮守ぢ 2020-11-29 06:35

What would be the best way to create a circularly linked list in C#. Should I derive it from the LinkedList< T> collection? I\'m planning on creating a simple address boo

10条回答
  •  失恋的感觉
    2020-11-29 07:06

    A modulus based solution.

    If the circular buffer is implemented as a raw array (or any other kind of collection for what it matters)

    T[] array;
    

    and we store into int current_index the index of the current item, we can cycle up and down the buffer as follows:

    T NextOrFirst()
    {
        return array[(current_index + 1) % array.Length];
    }
    
    T PreviousOrLast()
    {
        return array[(current_index + array.Length - 1) % array.Length];
    }
    

    The same approach can be used with any XAML binding collection.

提交回复
热议问题