| | |
| | | public abstract class BasePriorityQueue<T, TPriority> : Concurrent, IEnumerable<T>
|
| | | where TPriority : IComparable<TPriority>
|
| | | {
|
| | | SortedDictionary<TPriority, T> ItemsByPriority { get; set; }
|
| | | Dictionary<object, TPriority> ItemPriority { get; set; }
|
| | | SortedDictionary<TPriority, T> ItemsByPriority { get; }
|
| | | Dictionary<object, TPriority> ItemPriority { get; }
|
| | | T Head { get; set; }
|
| | | public int Count { get; private set; }
|
| | | public bool IsEmpty => (Count == 0);
|
| | |
| | | IEnumerator<T> IEnumerable<T>.GetEnumerator() => Items.GetEnumerator();
|
| | | IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator();
|
| | |
|
| | | Func<T, object> GetItemKey { get; set; }
|
| | | Func<T, object> GetItemKey { get; }
|
| | |
|
| | | public BasePriorityQueue() : this(x => x)
|
| | | { }
|
| | |
| | | if (item == null)
|
| | | throw new InvalidOperationException("Item cannot be null.");
|
| | | lock (CriticalSection) {
|
| | | T oldItem;
|
| | | if (ItemsByPriority.TryGetValue(priority, out oldItem) && !item.Equals(oldItem))
|
| | | if (ItemsByPriority.TryGetValue(priority, out T oldItem) && !item.Equals(oldItem))
|
| | | throw new InvalidOperationException("An item with the same priority exists.");
|
| | | TPriority oldPriority;
|
| | | if (ItemPriority.TryGetValue(GetItemKey(item), out oldPriority)) {
|
| | |
|
| | | if (ItemPriority.TryGetValue(GetItemKey(item), out TPriority oldPriority)) {
|
| | | ItemsByPriority.Remove(oldPriority);
|
| | | --Count;
|
| | | }
|
| | |
| | | public T Peek()
|
| | | {
|
| | | lock (CriticalSection) {
|
| | | T result;
|
| | | if (!TryPeek(out result))
|
| | | if (!TryPeek(out T result))
|
| | | throw new InvalidOperationException("Queue is empty.");
|
| | | return result;
|
| | | }
|
| | |
| | | public T Dequeue()
|
| | | {
|
| | | lock (CriticalSection) {
|
| | | T result;
|
| | | if (!TryDequeue(out result))
|
| | | if (!TryDequeue(out T result))
|
| | | throw new InvalidOperationException("Queue is empty.");
|
| | | return result;
|
| | | }
|