Skip to content

Queue

Last updated on September 26, 2019

Queue represents a line or a sequence of object waiting for their turn to be attended. Queue uses FIFO or first-in-first-out ordering where the first object enters the queue will also be the first to exit. Queue become useful if you would like to maintain the order of your objects to be processed later.

Imagine a real life example of queue, where you are at McDonald and the line continue to add up a person. With each person that is done ordering their food, they leave the line.

We will be using Protocol to build our queue.

  1. associatedtype is a way to make a protocol generic.
  2. enqueue means inserting an object at the end of the queue
  3. dequeue means removing the first object of the queue
  4. isEmpty essentially let us know if the queue is empty or not
  5. top returns the first object of the queue

Looking at the gif below will show you how the queue work in most real life.

Let’s start making Queue work in code.

Here, you’ve created a generic QueueArray that conform to Queue protocol. Note that the associatedtype object is inferred by the type parameter T.

Since you conform Queue, you have to define some of the function. Add the following code below.

  1. Check if the queue is empty or not
  2. Return the first object of the queue

Enqueue

Enqueue gives you the capabilities of adding an object to the back of the queue.

Dequeue

Dequeue gives you the capabilities of removing an object at the front of the queue.

Here, you check if the array is empty or not, if it’s empty, there isn’t anything to do. But if it’s not empty, you remove the first object of the queue.

Example of Queue

Now, let’s create the queue and start enqueue and dequeue.

With the code above, it creates a queue in the order that is being enqueued. With Kelvin being the first, it will show up as the first in the order which will be followed by the rest.

Now that, enqueue is working perfectly fine. Let’s test dequeue.

And that is Queue.

Published inAlgorithm

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © DaddyCoding 2020.