c# Adding a Remove(int index) method to the .NET Queue class

前端 未结 12 1533
攒了一身酷
攒了一身酷 2021-01-07 17:14

I would like to use the generic queue class as described in the .NET framework (3.5) but I will need a Remove(int index) method to remove items from the queue. Can I achieve

12条回答
  •  一整个雨季
    2021-01-07 17:34

    I do not believe we should be using List to emulate a queue, for a queue, the enqueue and dequeue operations should be very highly performant, which they would not be when using a List. For the RemoveAt method however, it is acceptable to be non-performant, as it is not the primary purpose of a Queue.

    My approach at implementing RemoveAt is O(n) but the queue still maintains a largely O(1) enqueue (sometimes the internal array needs reallocating which makes the operations O(n)) and always O(1) dequeue.

    Here is my implementation of a RemoveAt(int) extension method for a Queue:

    public static void RemoveAt(this Queue queue, int index)
    {
        Contract.Requires(queue != null);
        Contract.Requires(index >= 0);
        Contract.Requires(index < queue.Count);
    
        var i = 0;
    
        // Move all the items before the one to remove to the back
        for (; i < index; ++i)
        {
            queue.MoveHeadToTail();
        }
    
        // Remove the item at the index
        queue.Dequeue();
    
        // Move all subsequent items to the tail end of the queue.
        var queueCount = queue.Count;
        for (; i < queueCount; ++i)
        {
            queue.MoveHeadToTail();
        }
    }
    

    Where MoveHeadToTail is defined as follows:

    private static void MoveHeadToTail(this Queue queue)
    {
        Contract.Requires(queue != null);
    
        var dequed = queue.Dequeue();
        queue.Enqueue(dequed);
    }
    

    This implementation also modifies the actual Queue rather than returning a new Queue (which I think is more in-keeping with other RemoveAt implementations).

提交回复
热议问题