具有定义大小的特殊队列 [英] Special queue with defined size
问题描述
我需要一个大小有限的集合.它必须类似于循环缓冲区.我认为描述它的最快方法是举个例子.假设我有一个这个特殊"队列的实例,大小为 4.
I need a collection that is limited in its size. It has to be similar to a circular buffer. I think that the fastest way to describe it would be by making an example. Suppose I have an instance of this "special" queue, of size 4.
这是最初的队列:6 3 9 2
This is the queue initially: 6 3 9 2
如果我往里面推东西,它必须在开头添加它,删除最后一个元素并返回它的值,所以,如果我添加 3 它会变成:
If I push something into it, it has to add it at the beginning, remove the last element and return its value, so, if I add 3 it would become:
3 6 3 9 并返回 2
3 6 3 9 and returns 2
我希望我已经清楚了...通用实现就足够了,但 C# 实现将是最好的 :)
I hope I've been clear... A general implementation is sufficient, but a C# implementation would be the best :)
推荐答案
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();
}
}
这篇关于具有定义大小的特殊队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!