Зміст курсу
Algorithms and Data Structures Overview
Algorithms and Data Structures Overview
Queues
In contrast to stack, queues operate on a FIFO (First In, First Out) basis. Therefore, the first item inserted into a queue will be the first item removed. It means that for queues, we can manipulate only the first item exclusively. The queue data structure behavior resembles the queue in real life.
Queue implementation
import numpy as np class Queue: def __init__(self): self.queue = np.array([]) # Initialize an empty NumPy array def enqueue(self, item): self.queue = np.append(self.queue, item) # Add an item to the end of the queue def dequeue(self): if self.is_empty(): print("Queue is empty.") # Handle empty queue case gracefully return None # Return None if the queue is empty item = self.queue[0] # Get the first item from the queue self.queue = np.delete(self.queue, 0) # Remove the first item from the queue return item # Return the removed item def is_empty(self): return self.queue.size == 0 # Check if the queue is empty # Example usage: queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) print("Queue:", queue.queue) print("Dequeue:", queue.dequeue()) print("Queue after dequeue:", queue.queue) # Attempt to dequeue from an empty queue queue.dequeue() queue.dequeue() print("Dequeue from empty queue:", queue.dequeue()) # Should print 'Queue is empty.'
Queue is also an abstract data type. As well as stack, queue also defines two basic operations, insertion and deletion, which are implemented in two basic methods:
enqueue()
- inserts an element into an end of a queue;dequeue()
- removes a first element from a queue.
The queue abstract data type can be implemented with the help of both the array or linked list data structure.
Basic operations time complexity
Дякуємо за ваш відгук!