Introduction to Queue

What is a Queue?

A queue is an abstract data type that represents a collection of elements with a first-in, first-out (FIFO) behavior. It can be visualized as a line of objects, where new elements are added to the back and removed from the front.

In a queue, the element that is added first is the first one to be removed, following the First-In-First-Out principle. This behavior is often referred to as "enqueue" for adding elements to the queue and "dequeue" for removing elements from the queue.

The main operations associated with a queue are:

Enqueue: This operation adds an element to the back (end) of the queue.

Dequeue: This operation removes and returns the element from the front (beginning) of the queue.

Front/Peek: This operation returns the element at the front of the queue without removing it.

A real-life example of a queue can be observed in a queue of people waiting in line at a ticket counter, a checkout counter in a store, or a queue of vehicles waiting at a toll booth. 

Queues are commonly used in various scenarios where elements need to be processed in the order of their arrival, such as task scheduling, job processing, and event handling.

The queue data structure can be implemented using various programming languages and underlying data structures. Arrays, linked lists, and doubly linked lists are commonly used for implementing queues.

Queue Operations(Push, Pop, Top/Peek)

Here's an example of implementing a queue using a list (array) in Python:

class Queue:

    def __init__(self):

        self.queue = []


    def is_empty(self):

        return len(self.queue) == 0


    def enqueue(self, element):

        self.queue.append(element)


    def dequeue(self):

        if not self.is_empty():

            return self.queue.pop(0)

        else:

            raise Exception("Queue is empty")


    def front(self):

        if not self.is_empty():

            return self.queue[0]

        else:

            raise Exception("Queue is empty")


In this example, the Queue class represents a queue and provides methods to perform queue operations:

is_empty(): Checks if the queue is empty.

enqueue(element): Adds an element to the back of the queue.

dequeue(): Removes and returns the element from the front of the queue.

front(): Returns the element at the front of the queue without removing it.


You can create an instance of the Queue class and perform queue operations on it:

my_queue = Queue()


my_queue.enqueue(10)

my_queue.enqueue(20)

my_queue.enqueue(30)


print(my_queue.dequeue())  # Output: 10

print(my_queue.front())  # Output: 20

print(my_queue.is_empty())  # Output: False