Welcome to another exciting tutorial! Today, we're going to learn how to implement a Queue using an Array š. This data structure is essential for handling tasks that come in sequentially but need to be processed in the order they arrive. Let's dive in!
A Queue is a collection of elements ordered in a sequential manner where the addition and removal of elements follows a specific rule: elements are added at the back (rear) and removed from the front (front). This order is often referred to as First-In-First-Out (FIFO).
Queues are useful in various scenarios such as managing tasks in an operating system, handling requests in a web server, and optimizing graph traversal algorithms. Let's get our hands dirty and implement a Queue using an Array!
To represent a Queue, we'll use an Array, and two additional variables: front and rear, which keep track of the position of the first and last elements in the queue, respectively.
queue = []
front = -1
rear = -1We'll create three main functions: enqueue, dequeue, and is_empty.
enqueue(item): Adds an item to the rear of the queue.def enqueue(item):
global queue, rear
queue.append(item)
rear += 1dequeue(): Removes and returns the front item from the queue.def dequeue():
global queue, front, rear
if is_empty():
return None
front += 1
item = queue[front]
queue[front] = None
if front > rear:
front = rear = -1
return itemis_empty(): Checks if the queue is empty.def is_empty():
return front == -1Imagine you're running a small print shop. Customers arrive and place orders one after the other. You will process the orders in the order they were received (FIFO).
queue = []
customers = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
for customer in customers:
enqueue(customer)
while not is_empty():
print('Printing:', dequeue())Output:
Printing: Alice
Printing: Bob
Printing: Charlie
Printing: David
Printing: Eve
What is the main difference between a Queue and a Stack?
What happens if you try to `dequeue()` from an empty Queue?