C# Data Structures – Queue

Continuing on from my article about Stacks we are going to look at the Queue Data Structure.  Queue is similar to the Stack with one difference it follows First in First out.  By default the initial capacity of a queue is 32 items.  Like stacks, this is customizable. 

The queue supports the following methods:

  • Enqueue – Push items into the queue
  • Dequeue – pop item off the queue
  • Peek – view what item is on top
  • Contains – Boolean check to see if the queue contains an item

Here is an example of a queue.

var queue = new Queue();

queue.Enqueue("dog");
queue.Enqueue("lazy");
queue.Enqueue("the");
queue.Enqueue("over");
queue.Enqueue("jumps");
queue.Enqueue("fox");
queue.Enqueue("brown");
queue.Enqueue("quick");
queue.Enqueue("the");

Console.WriteLine("Peek the stack, returns {0}", queue.Peek());

Console write line will print out the word ‘dog’.   Now to show the flow of the queue, add the following:

queue.Dequeue();
queue.Enqueue("today");

var sentence = string.Empty;
while (queue.Count > 0)
{
    sentence += " " + queue.Peek();
    queue.Dequeue();
}

Console.WriteLine("After we pop all the items in the stack this is the sentence we have \n {0}", sentence);

After we run this example the sentence will change to this “lazy the over jumps fox brown quick the today”

Advertisement
This entry was posted in C# and tagged , . Bookmark the permalink.