Fundamentals 7 min read

Queue Essentials – Master FIFO for Queuing and Message Push

This tutorial explains the FIFO principle of queues with everyday analogies, compares stacks and queues, lists core operations, provides a full Python implementation, demonstrates real‑world scenarios like server requests and printer jobs, and highlights common beginner pitfalls.

liandk
liandk
liandk
Queue Essentials – Master FIFO for Queuing and Message Push

What Is a Queue?

Queues follow the First‑In‑First‑Out (FIFO) rule, meaning the first element added is the first to be removed.

Everyday analogy: a supermarket checkout line where the person who joins the line first is served first, later arrivals must wait at the tail, and the front of the line is served before anyone behind.

Who queues first, checks out first.

Later arrivals can only stand at the end; no cutting in line.

The person at the front leaves the queue first.

Core Queue Operations (Must‑Know)

Enqueue : add data to the tail of the queue.

Dequeue : remove data from the head of the queue.

Stack vs. Queue – Ultimate Comparison

Stack (LIFO) – like a stack of chips: the last item placed is the first removed (useful for undo, backtracking).

Queue (FIFO) – like a supermarket line: the first person in line is the first to be served (useful for scheduling, distribution).

Mnemonic for beginners: “Stack reverses, queue preserves order.”

Real‑World Use Cases

Food‑delivery orders, cafeteria lines, hospital call‑number systems.

Server request queuing when many users access a website simultaneously.

Message ordering in chat applications (e.g., WeChat).

Printer job scheduling – multiple files waiting to be printed.

Underlying mechanism of breadth‑first search (BFS) algorithm.

Complete Queue Code (Python)

class Queue:
    def __init__(self):
        # Initialize an empty queue
        self.queue = []

    # 1. Enqueue: add element at the tail
    def enqueue(self, data):
        self.queue.append(data)

    # 2. Dequeue: remove and return element from the head
    def dequeue(self):
        if self.is_empty():
            return "Queue is empty, cannot dequeue"
        return self.queue.pop(0)

    # 3. Get front element
    def get_front(self):
        if self.is_empty():
            return "Queue is empty"
        return self.queue[0]

    # 4. Check if queue is empty
    def is_empty(self):
        return len(self.queue) == 0

    # 5. Get queue length
    def get_length(self):
        return len(self.queue)

    # 6. Clear the queue
    def clear(self):
        self.queue = []

# ========== Simple test run ==========
if __name__ == "__main__":
    q = Queue()
    q.enqueue("User1")
    q.enqueue("User2")
    q.enqueue("User3")
    print("Current queue:", q.queue)
    print("Front element:", q.get_front())
    print("Queue length:", q.get_length())
    print("Dequeued:", q.dequeue())
    print("Remaining queue:", q.queue)
    q.clear()
    print("Is queue empty:", q.is_empty())

Code Execution Result

Current queue: ['User1', 'User2', 'User3']

Front element: User1

Queue length: 3

Dequeued: User1

Remaining queue: ['User2', 'User3']

Is queue empty: True

Practical Printer‑Queue Example

# Simulate printer queue
printer_queue = Queue()

# Add print jobs in order
printer_queue.enqueue("Document1.pdf")
printer_queue.enqueue("Resume.docx")
printer_queue.enqueue("Report.xlsx")
print("Pending jobs:", printer_queue.queue)

# Print jobs sequentially
print("Printing:", printer_queue.dequeue())
print("Printing:", printer_queue.dequeue())
print("Remaining jobs:", printer_queue.queue)

Running the above yields:

Pending jobs: ['Document1.pdf', 'Resume.docx', 'Report.xlsx']

Printing: Document1.pdf

Printing: Resume.docx

Remaining jobs: ['Report.xlsx']

Common Pitfalls for Beginners

Strictly follow FIFO; do not delete or insert elements in the middle of the queue.

Dequeue on an empty queue raises an error – always check emptiness first.

Simple queue dequeue performance can be low; a circular queue can improve efficiency (to be covered later).

Next Episode Preview

Episode 5 will introduce the circular queue, an optimized version that eliminates space waste, and is a frequent interview topic.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AlgorithmPythonData StructuresQueueBFSFIFOStack vs Queue
liandk
Written by

liandk

Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.