Last active
December 20, 2016 21:29
-
-
Save lukasz-pyrzyk/cf46b317914923103594df9eb73af26f to your computer and use it in GitHub Desktop.
A Priority queue of T based on IComparable
This file contains 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; | |
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