Created
February 3, 2019 22:53
-
-
Save jackmott/9753f02dcd33a1267fbc4504c516241a to your computer and use it in GitHub Desktop.
priority queue in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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