Skip to content

Instantly share code, notes, and snippets.

@lukasz-pyrzyk
Last active December 20, 2016 21:29
Show Gist options
  • Save lukasz-pyrzyk/cf46b317914923103594df9eb73af26f to your computer and use it in GitHub Desktop.
Save lukasz-pyrzyk/cf46b317914923103594df9eb73af26f to your computer and use it in GitHub Desktop.
A Priority queue of T based on IComparable
using System;
using System.Collections;
using System.Collections.Generic;
namespace ProjectForTests
{
public class PriorityQueue<T> : IEnumerable<T> where T : IComparable<T>
{
private readonly LinkedList<T> _items = new LinkedList<T>();
public void Enqueue(T item)
{
if (_items.Count == 0)
{
_items.AddLast(item);
}
else
{
var current = _items.First;
while (current != null && current.Value.CompareTo(item) > 0)
{
current = current.Next;
}
if (current == null)
{
_items.AddLast(item);
}
else
{
_items.AddBefore(current, item);
}
}
}
public T Dequeue()
{
if (_items.Count == 0)
{
throw new InvalidOperationException("Queue is empty");
}
T value = _items.First.Value;
_items.RemoveFirst();
return value;
}
public T Peek()
{
if (_items.Count == 0)
{
throw new InvalidOperationException("Queue is empty");
}
return _items.First.Value;
}
public IEnumerator<T> GetEnumerator()
{
return _items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment