Skip to content

Instantly share code, notes, and snippets.

@victoraldecoa
Created September 11, 2021 13:33
Show Gist options
  • Save victoraldecoa/30a6963226dc635edf84ae9e53cecbb2 to your computer and use it in GitHub Desktop.
Save victoraldecoa/30a6963226dc635edf84ae9e53cecbb2 to your computer and use it in GitHub Desktop.
C# PriorityQueue that allows repeated values implemented using SortedDictionary.
public class PriorityQueue<T>
{
readonly SortedDictionary<T, int> dict;
public PriorityQueue()
{
dict = new SortedDictionary<T, int>();
}
public PriorityQueue(IComparer<T> comparer)
{
dict = new SortedDictionary<T, int>(comparer);
}
public PriorityQueue(IEnumerable<T> coll)
{
dict = new SortedDictionary<T, int>();
AddMany(coll);
}
public PriorityQueue(IEnumerable<T> coll, IComparer<T> comparer)
{
dict = new SortedDictionary<T, int>(comparer);
AddMany(coll);
}
public void AddMany(IEnumerable<T> coll)
{
foreach (var val in coll)
{
Add(val);
}
}
public void Add(T value)
{
if (dict.ContainsKey(value)) dict[value]++;
else dict[value] = 1;
}
public T Top()
{
return dict.Any() ? dict.First().Key : default;
}
public void Remove(T value)
{
var count = dict[value];
if (count > 1) dict[value] = count - 1;
else dict.Remove(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment