This program demonstrates the implementation of a queue data structure using a linked list. Queues are a type of data structure with First In First Out (FIFO) access policy. The operations demonstrated in this queue are:

  • Enqueue: Add an item to the end of the queue.
  • Dequeue: Remove the item from the front of the queue.
  • Peek: Get the item at the front of the queue without removing it.
  • is_empty: Check if the queue is empty.

Code Explanation

The queue functionality is encapsulated within a class Queue. This class uses an inner class Node, which represents an element in the queue. Here’s a detailed breakdown of the methods within the Queue class:

  1. Node class: A simple class for storing data and the link to the next node.
  2. __init__: Initializes the queue.
  3. enqueue: Adds a new element to the end of the queue.
  4. dequeue: Removes the element from the front of the queue and returns it.
  5. peek: Returns the front element without removing it.
  6. is_empty: Returns True if the queue is empty, otherwise False.

Python Code

class Queue:
    class Node:
        def __init__(self, value):
            self.value = value
            self.next = None

    def __init__(self):
        self.head = None
        self.tail = None

    def enqueue(self, item):
        new_node = self.Node(item)
        if self.tail:
            self.tail.next = new_node
        self.tail = new_node
        if not self.head:
            self.head = new_node

    def dequeue(self):
        if self.is_empty():
            raise IndexError("dequeue from empty queue")
        current_head = self.head
        self.head = self.head.next
        if not self.head:
            self.tail = None
        return current_head.value

    def peek(self):
        if self.is_empty():
            raise IndexError("peek from empty queue")
        return self.head.value

    def is_empty(self):
        return self.head is None

Usage

To use this queue, instantiate an object of the Queue class and use the enqueue, dequeue, and peek methods to manipulate it.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)