Special queue with defined size

2019-05-15 05:00发布

问题:

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.

This is the queue initially: 6 3 9 2

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 and returns 2

I hope I've been clear... A general implementation is sufficient, but a C# implementation would be the best :)

回答1:

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();
    }
}


回答2:

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();
    }
}


标签: c# stack queue