Data Structures - Queue


2 min read

Imagine a queue is like a line at your favorite amusement park ride. People join the line (enqueue) at the back and exit (dequeue) from the front. Here is the catch: you can't just jump ahead of everyone else! The first person who joined the line gets on the ride first. Just like that, a queue follows the "First In, First Out" (FIFO) rule. So, in essence, a queue is like a well-behaved line of people, patiently waiting for their turn, ensuring fairness and order in processing tasks or data.

Come and join me in implementing a queue using Python.

Note: To avoid conflicts with Queue class in the Python standard library, we define a custom MyQueue class.

from typing import Any, Optional

class MyQueue:
    def __init__(self) -> None:
        self.items: list = []

    def is_empty(self) -> bool:
        return len(self.items) == 0

    def size(self) -> int:
        return len(self.items)

    def enqueue(self, item: Any) -> None:
        self.items.insert(0, item)

    def dequeue(self) -> Optional[Any]:
        if not self.is_empty():
            return self.items.pop()
            return None

Message queue is the most intuitive application of queue. Now use MyQueue to implement a simple message queue.

from my_queue import MyQueue
from typing import Any, Optional

class MessageQueue:
    def __init__(self):
        self.queue = MyQueue()

    def send_message(self, message: Any) -> None:
        print("Message sent:", message)

    def receive_message(self) -> Optional[Any]:
        if not self.queue.is_empty():
            return self.queue.dequeue()
            return None

def main() -> None:        
    mq = MessageQueue()
    mq.send_message("hello, world")
    mq.send_message("this is python")



if __name__ == "__main__":

Message sent: hello, world
Message sent: this is python
Message sent: ketechy
hello, world
this is python