minte9
LearnRemember




Queues

A queue is similar to a stack, except that is processes data in a different order. Queue are display and explain horizontaly. It's like a line of people at the movie theater. The first one in line is the first one to leave and enter the theater (FIFO).

Deque / Python

In Python, queues are a buit-in data structure with its own standard library. Deque in python is a versatile implementation of double-ended queue. It allows you to effectively use it as a stack, a queue, or a combination of both.
 
from collections import deque

# Initialize the queue
my_queue = deque()

# Add elements to the back of the queue
my_queue.append(1)
my_queue.append(2)
my_queue.append(3)

# Output queue
print("Queue after insertion =", my_queue)

# Remove from the front of the queue
front = my_queue.popleft()

# Output queue 
print("Queue after deletion =", my_queue)
print("Popped left element =", front)

"""
    Queue after insertion = deque([1, 2, 3])
    Queue after deletion = deque([2, 3])
    Popped left element = 1
"""

Create Queue

Like many other abstarct data types, it isn't implemented in many programming languages. Let's create a queue to see how it works internaly.
 
class Queue:
    def __init__(self):
        self.items = []

    def append(self, item):
        self.items += [item]

    def popleft(self):
        item = self.items[0]
        self.queue = self.items[1:]
        return item

    def read(self):
        return self.items[0]

    def __str__(self):
        return str(self.items)

# New queue
queue = Queue()

# Push elements into the queue
queue.append(1)
queue.append(2)
queue.append(3)

# Output queue
print("Queue after insertion =", queue)

# Remove from the queue
popped = queue.popleft()
print("Remove from queue front =", popped)
print("Queue after deletion =", queue)

# Read from queue
print("New front =", queue.read())       

"""
    Queue after insertion = [1, 2, 3]
    Remove from queue front = 1
    Queue after deletion = [1, 2, 3]
    New front = 1
"""



  Last update: 224 days ago