Stores a collection of elements that can only be modified by adding elements at one end of the sequence and removing at the other end - FIFO
Main operations
enqueue and dequeue
front, isFull, isEmpty
Implementation
Singly vs. doubly linked lists for queues
Since nodes in a normal singly linked list don’t have a previous reference, when enqueuing, it takes O(n) time to traverse to and update the the second-last node’s next reference to the added node
(Presuming the head points to the front of the queue)
This implementation is efficient because adding elements to the tail of the list and removing elements from the head of the list can be done in constant time.
Circular array
Use a dynamically resizing array with front/back pointers and modulo operations for when the queue wraps around
Python resizable array implementation
class Queue: def __init__(self, capacity=10): self.front = 0 # Initialize front pointer to 0 self.rear = 0 # Initialize rear pointer to 0 self.capacity = capacity # Set maximum capacity of the queue self.queue = [None] * capacity # Create an array of None values with length capacity def is_empty(self): return self.front == self.rear def is_full(self): return (self.rear + 1) % len(self.queue) == self.front def enqueue(self, item): if self.is_full(): self._resize() self.queue[self.rear] = item # Add item to the rear of the queue self.rear = (self.rear + 1) % len(self.queue) # Increment rear pointer def dequeue(self): if self.is_empty(): raise Exception("Queue is empty") item = self.queue[self.front] # Get the item at the front of the queue self.queue[self.front] = None # Remove the item from the queue by setting it to None self.front = (self.front + 1) % len(self.queue) # Increment front pointer if len(self.queue) > self.capacity and len(self.queue) // 4 == self.capacity: self._resize() return item def _resize(self): old_queue = self.queue self.capacity = len(old_queue) * 2 self.queue = [None] * self.capacity i = 0 while not self.is_empty(): self.queue[i] = self.dequeue() i += 1 self.front = 0 self.rear = i
Circular queue
a data structure that uses a fixed-size array to implement a queue where the front and rear of the queue are connected.
start with a fixed-size array to store the elements of the queue.
We’ll need to keep track of the front and rear of the queue, which will initially both be set to zero.
Restricted deque
Use a deque but impose the restriction that elements can only be inserted at the back of the deque and removed from the front of the deque.