题目内容
Circular Array: Implement a circular array class that supports an array-like data structure which can be efficiently rotated. If possible, the class should use a generic type, and support iteration via standard for (Obj o:circularArray) notation.
定义:https://zh.wikipedia.org/wiki/%E7%92%B0%E5%BD%A2%E7%B7%A9%E8%A1%9D%E5%8D%80
缓冲区中总是有一个存储单元保持未使用状态。缓冲区最多存入个数据。如果读写指针指向同一位置,则缓冲区为空。如果写指针位于读指针的相邻后一个位置,则缓冲区为满。这种策略的优点是简单、鲁棒;缺点是语义上实际可存数据量与缓冲区容量不一致,测试缓冲区是否满需要做取余数计算。
/// <summary>
/// implement a circular array, with primitive array type with these metho
// boolean isEmpty()
// boolean isFull()
// insert(int i)
// delete()
/// </summary>
/// <typeparam name="T"></typeparam>
public class CircularArray<T>
{
T[] items;
//head 读指针; tail写指针;
int head = 0,tail=0;
int capacity;
public int Head
{
get
{
return head;
}
set
{
head = value;
}
}
public int Capacity
{
get
{
return capacity;
}
set
{
capacity = value;
}
}
public CircularArray(int size)
{
capacity = size;
items = new T[size];
}
private int Convert(int index)
{
while (index < 0)
{
index += items.Length;
}
return (Head + index) % items.Length;
}
// 如果缓冲区是满的,又要写入新的数据,一种策略是覆盖掉最老的数据。
// 总是保持一个存储单元为空,缓冲区中总是有一个存储单元保持未使用状态。
// 缓冲区最多存入 {\displaystyle {\text{(size}}-1)} {\displaystyle {\text{(size}}-1)}个数据。
// 如果读写指针指向同一位置,则缓冲区为空。如果写指针位于读指针的相邻后一个位置,则缓冲区为满。
// 这种策略的优点是简单、鲁棒;缺点是语义上实际可存数据量与缓冲区容量不一致,测试缓冲区是否满需要做取余数计算。
public void Insert(T t)
{
items[tail] = t;
if (IsFull())
{
head++;
}
head = head % capacity;
tail++;
tail = tail % capacity;
}
//FIFO,先进先出,类似Queue;返回head指针内容;
public T Delete()
{
if (IsEmpty())
return default(T);
T t = items[head];
items[head] = default(T);
head++;
head = head % capacity;
return t;
}
//总是保持一个存储单元为空; 如果tail位于head的前的一个位置,则缓冲区为满。
public bool IsFull()
{
return (Convert(head) - Convert(tail))==1;
}
//总是保持一个存储单元为空; 如果head,tail指针指向同一位置,则缓冲区为空。
public bool IsEmpty()
{
return head == tail;
}
}