Skip to content

Instantly share code, notes, and snippets.

@jackmott jackmott/pqueue.cs
Created Feb 3, 2019

Embed
What would you like to do?
priority queue in c#
using System.Collections.Generic;
using System.Linq;
namespace FB
{
public class PQueue<T>
{
private SortedDictionary<float, Stack<T>> sdict;
public PQueue()
{
sdict = new SortedDictionary<float, Stack<T>>();
}
public void Put(T thing, float priority)
{
if (sdict.ContainsKey(priority))
{
sdict[priority].Push(thing);
} else
{
var s = new Stack<T>();
s.Push(thing);
sdict.Add(priority,s);
}
}
public T Get()
{
var kvp = sdict.ElementAt(0);
var result = kvp.Value.Pop();
if (kvp.Value.Count == 0)
{
sdict.Remove(kvp.Key);
}
return result;
}
public bool Empty()
{
return sdict.Count == 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.