Queue Data Structure

Kevin Gicheha
3 min readNov 17, 2022

--

Part 1: Implementing Queue Using Arrays

A queue is a data structure that follows the First-In/First-Out principle(popularly known as FIFO), meaning the first element that’s added will be the first to be removed.

Queues at the supermarket

List of Queue Operations

// Add an item to the end of queue
.enqueue(item)

// Remove item from front of queue
.dequeue()

// Get the first item without removing it
.front()

// Get the last item
.rear()

// Check if queue is empty
.IsEmpty()

// Check if queue is full
.isFull()

// Return size of the queue
.size()

Types of Queues

  1. Simple Queue: insertion of an element takes place at the rear end and the removal takes place at the front end.
  2. Priority Queue: arranges the elements in a queue based on some priority. An example can be where an element with a higher value is placed at the front. This would organize the queue in descending order based on the values.
  3. Circular Queue: this works very similarly to the simple queue. The difference is that the last element is connected back to the first element, thus forming a circular ring.

Implement A Simple Queue Using Array

class Queue{

constructor(){
this.items = []
}

// add item to queue
enqueue(item){
this.items.push(item)
}

// remove item from queue
dequeue(){
if(this.items.length > 0){
return this.items.shift()
} else {
return "Underflow Situation"
}
}

// check to see if queue is empty
isEmpty(){
return this.items.length === 0
}

front(){
if(this.items.length === 0){
return "No items in Queue"
}
return this.items[0]
}
}

// create new instance of Queue
const queue1 = new Queue();

Time and Space Complexity

Time & Space Complexity

Applications of Queue Data Structure

  1. Adding songs to a playlist on a music streaming service, like Tidal, Spotify, or Apple Music. The songs are added at the bottom of the playlist. They are then played in the order in which they are listed unless the shuffle option is selected.
  2. Waitlists for a single shared resource, like CPU, or printers. When documents get sent to printers, they are printed out in the order in which they are received.
  3. When uploading multiple images, the first image that’s entered will be the first image that is processed.

Check out Part 2: Implementing Queues Using Linked List

Citation

https://devopedia.org/queue-data-structure#:~:text=complexity%20of%20queues.-,Source%3A%20Devopedia%202022.,longer%20if%20resizing%20is%20required.

--

--