使用C#中的排序字典在优先级队列中出列

时间:2014-03-10 05:59:33

标签: c# dictionary priority-queue sorteddictionary

我有一个表格的排序字典:

SortedDictionary<PriorityType, List<T>> dictionary;

其中PriorityType是枚举类。

现在我正在尝试制作优先队列方法,但我担心我的Dequeue方法是否有效。

public T Dequeue()
    {
        if (IsEmpty())
        {
            throw new Exception("The Priority Queue is empty! Dequeuing is not possible!");
        }

        var highestPriorityList = dictionary[dictionary.Keys.First()];
        var topElement = highestPriorityList.FirstOrDefault();
        if (highestPriorityList.Count == 0)
        {
            dictionary.Remove(dictionary.Keys.First());
        }
        highestPriorityList.RemoveAt(0);
        return topElement;
    }

请帮我改进这种方法!

注意:Dequeue()方法应该删除并返回具有最高优先级的对象,并且该对象优先于具有相同优先级的其他元素。

1 个答案:

答案 0 :(得分:1)

好的,所以我能够修改上面的代码以适合我的出队操作!

public T Dequeue()
    {
        var highestPriorityList = dictionary[dictionary.Keys.First()];
        if (highestPriorityList.Count == 0)
        {
            dictionary.Remove(dictionary.Keys.First());
        }
        var topElement = highestPriorityList.First();
        highestPriorityList.Remove(topElement);
        return topElement;
    }

现在我可以在没有InvalidOperationException的情况下出列队列,这是由RemoveAt操作后列表中缺少的元素引起的!

相关问题