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
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.
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.
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() { }
}
How about this CList based circular list.