Priority Queue with C#

Basilin Joe
2 min readMay 8, 2020

--

Photo by Curtis MacNewton on Unsplash

A priority queue is like a regular queue, but with priority. Instead of always serving the first one it serves the one with the most priority. So what if both have the same priority? As it is a queue whichever comes first will be served first.

The approach I use will stress on insert(Enqueue) functions to put the elements in the order of priority in the queue. ie; if the initial value of the queue was 1,5,8 and you enqueue element with priority 6 it will be placed between 5 and 8. To remove(dequeue) all you have to do is pop the first element. The hight priority will be for value 1 and I will be using the linked-list to implement the priority queue

Let’s do the coding

C# provides us with a generic `LinkedList<T>` class with all the necessary functionalities. So what is left to do is the prioritized insertion. I wanted to go for a generic implementation so that anyone can use this priority queue. So let’s create an interface with a definition of priority. Let’s call it IPrioritizable. Any implementation of IPrioritizable can be inserted into the priority queue.

The PriorityQueue class that we are going to create should have :

  1. Enqueue function to insert into the queue
  2. Dequeue function to pop the most prioritized item
  3. Count function
  4. Entries property of type LinkedList

Let’s create the class `PriorityQueue<TEntry>`

Now that the queue is created, need to create something to add to it. Here is a `SuperHero` class that implements the `IPrioritizable` interface.

Now all the components are ready, let's cook the main program.

Output

--

--