我需要一个大小有限的集合。它必须类似于循环缓冲区。我认为描述它的最快方法是举个例子。假设我有一个大小为 4 的“特殊”队列的实例。
这是最初的队列:6 3 9 2
如果我往里面推一些东西,它必须在开头添加它,删除最后一个元素并返回它的值,所以,如果我添加 3 它会变成:
3 6 3 9 并返回 2
我希望我已经很清楚了......一般的实现就足够了,但是 C# 实现将是最好的:)
public class MyQueue<T>
{
private Queue<T> queue;
public MyQueue(int capacity)
{
Capacity = capacity;
queue = new Queue<T>(capacity);
}
public int Capacity { get; private set; }
public int Count { get { return queue.Count; } }
public T Enqueue(T item)
{
queue.Enqueue(item);
if (queue.Count > Capacity)
{
return queue.Dequeue();
}
else
{
//if you want this to do something else, such as return the `peek` value
//modify as desired.
return default(T);
}
}
public T Peek()
{
return queue.Peek();
}
}
public class FixedQueue<T> : IEnumerable<T>
{
private LinkedList<T> _list;
public int Capacity { get; private set; }
public FixedQueue(int capacity)
{
this.Capacity = capacity;
_list = new LinkedList<T>();
}
public T Enqueue(T item)
{
_list.AddLast(item);
if (_list.Count > Capacity)
return Dequeue();
return default(T);
}
public T Dequeue()
{
if (_list.Count == 0)
throw new InvalidOperationException("Empty Queue");
var item = _list.First.Value;
_list.RemoveFirst();
return item;
}
public T Peek()
{
if (_list.Count == 0)
throw new InvalidOperationException("Empty Queue");
return _list.First.Value;
}
public void Clear()
{
_list.Clear();
}
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _list.GetEnumerator();
}
}