Sounds familiar?

Let’s see in detail!

Queue Data Structure

Introduction

A Queue is a linear data structure that follows FIFO (First-In First-Out) Ordering. Queue allows insertion of elements at one end(front) and deletion of elements on the other end(rear). A real-life scenario in the form of example for queue will be the queue of students waiting at the college book bank, queue is also used within computer systems for CPU Scheduling and Disk Scheduling.

Operations on Queue

Enqueue: Inserts an item into the back of the queue.

Inserts an item into the back of the queue. Dequeue: Removing the front item from the queue.

Queue Implementation using Array

For the array implementation, we will keep track of the following factors: current size, maximum size/capacity, index of front element and index of rear element. While creating a queue, capacity will be fixed by the user. Write a class Queue and initialize the data members using a parametrized constructor.

Initial State

The following functions are written before writing the Enqueue and Dequeue functions.

Empty(): Tells whether the queue is empty or not Full():Tells whether the queue is empty or not frontElement(): Returns the element at front

Queue Class

Enqueue Fuction

The enqueue function takes data(to be entered in the queue) as a parameter. It first checks if the queue has space for a new element or not using Full() function. If the queue is not full, it increments the rear index, puts the data at the rear index and increments the current size by one. It increments the index in a circular manner by using the formula:

rear = (rear+1)%maximumSize

This makes sure that the rear index doesn’t go out of range.

Enqueue Function

Dequeue Function

The dequeue function first checks if there are any elements to be removed by using Empty() function. If the queue is non empty, it increments the front index and decrements the current size by one. It increments the index in a circular manner similar to rear by using theformula:

front = (front+1)%maximumSize;

Enqueue and Dequeue Operations

Dequeue Function

Time Complexity:

Time complexity of both Enqueue() and Dequeue() operations is O(1) as we are not using any loop or recursive calls in the functions.

Source Code:

For the complete source code visit: