0
0
DSA Pythonprogramming~3 mins

Why Enqueue Using Linked List in DSA Python?

Choose your learning style9 modes available
The Big Idea

What if adding to a line could be as simple as just linking a new person at the end, no shuffling needed?

The Scenario

Imagine you have a long line of people waiting to buy tickets. You try to add each new person by shifting everyone one step back manually. This takes a lot of time and effort as the line grows.

The Problem

Manually moving each person back every time someone new arrives is slow and tiring. It's easy to make mistakes, like losing track of who is next or accidentally skipping someone.

The Solution

Using a linked list to add people at the end of the line lets you quickly add new arrivals without moving anyone else. You just connect the new person to the end, making the process fast and error-free.

Before vs After
Before
queue = [1, 2, 3]
new_person = 4
queue = queue + [new_person]  # Shifts everyone manually
After
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Queue:
    def __init__(self):
        self.front = None
        self.rear = None

    def enqueue(self, data):
        new_node = Node(data)
        if self.rear is None:
            self.front = new_node
            self.rear = new_node
        else:
            self.rear.next = new_node
            self.rear = new_node
What It Enables

This lets you build queues that grow smoothly and quickly, no matter how many items you add.

Real Life Example

Think of a printer queue where documents arrive one after another. Using a linked list to enqueue documents means the printer can handle any number of print jobs efficiently.

Key Takeaways

Manually adding to a queue by shifting elements is slow and error-prone.

Linked list enqueue adds new items at the end quickly without moving others.

This method keeps queues efficient and easy to manage as they grow.