Skip to content

Instantly share code, notes, and snippets.

@jackmott
Created February 3, 2019 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackmott/9753f02dcd33a1267fbc4504c516241a to your computer and use it in GitHub Desktop.
Save jackmott/9753f02dcd33a1267fbc4504c516241a to your computer and use it in GitHub Desktop.
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