Monday 4 May 2015

Queue

The queue is a First in First out data structure or fifo, it's the way your printer "Queue" works. The c# implementation of the queue has various additional functions, you can read all about it on the MSDN docs but at its core the queue uses the following:
  • Enqueue: adds an item to the queue
  • Dequeue: returns & removes the oldest item in the queue
  • Peek: looks at the oldest item in the queue 
You can think of it as a line-up of people to get ice cream, whoever get's in line first, gets served first 


That is pretty much if for the most basic of queues, notice that in our implementation of our queue below, we mix and match our types, the basic implementation of the queue is indifferent to what type of object is stored inside it, it's not used for sorting, it is a sequential data-structure used to maintain order


namespace pav.queue;

using System;
using System.Collections;

public class Person{
public string Name { get; set; }
public Person(string name) => this.Name = name;
public override string ToString() => this.Name;
}

class Program
{
static void Main(string[] args)
{
var q = new Queue();

q.Enqueue("one");
q.Enqueue("Two");
q.Enqueue(3);
q.Enqueue("Four");
q.Enqueue("Five");
q.Enqueue(new Person("pawel"));
q.Enqueue(6.0);
q.Enqueue("Seven");

Console.WriteLine("Count after enqueue {0}\n", q.Count);

while (q.Count > 0)
Console.WriteLine(q.Dequeue());

Console.WriteLine("\nCount after Dequeue {0}", q.Count);
}
}


The queue is exactly what it sounds like, it's a line of things in which the thing at the front of the line is next and anything added after goes to the back.

One thing to make not of is that there is a more modern implementation of the Queue using generics, this let's you restrict your queue's data type, you can read about it again on the MSDN docs

A Quick implementation would simply be to restrict our queue above to only accept strings.


namespace pav.queue;

using System;
using System.Collections;

public class Person{
public string Name { get; set; }
public Person(string name) => this.Name = name;
public override string ToString() => this.Name;
}

class Program
{
static void Main(string[] args)
{
var q = new Queue<string>();

q.Enqueue("one");
q.Enqueue("Two");
//q.Enqueue(3);
q.Enqueue("Four");
q.Enqueue("Five");
//q.Enqueue(new Person("pawel"));
//q.Enqueue(6.0);
q.Enqueue("Seven");

Console.WriteLine("Count after enqueue {0}\n", q.Count);

while (q.Count > 0)
Console.WriteLine(q.Dequeue());

Console.WriteLine("\nCount after Dequeue {0}", q.Count);
}
}


Notice that when we declare our Queue, we specify the type which the queue will contain.