Creating a circularly linked list in C#?

后端 未结 10 1087
独厮守ぢ
独厮守ぢ 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.

    0 讨论(0)
  • 2020-11-29 07:14

    Do you have a specific requirement to use a circularly linked list (i.e. homework)? If not, I would suggest using the simple List<T> class to store your contacts.

    0 讨论(0)
  • 2020-11-29 07:16
    class CircularArray<T> : IEnumerator<T>
    {
        private readonly T[] array;
        private int index = -1;
        public T Current { get; private set; }
    
        public CircularArray(T[] array)
        {
            Current = default(T);
            this.array = array;
        }
    
        object IEnumerator.Current
        {
            get { return Current; }
        }
    
        public bool MoveNext()
        {
            if (++index >= array.Length)
                index = 0;
            Current = array[index];
            return true;
        }
    
        public void Reset()
        {
            index = -1;
        }
    
        public void Dispose() { }
    }
    
    0 讨论(0)
  • 2020-11-29 07:17

    How about this CList based circular list.

    0 讨论(0)
提交回复
热议问题