A Queue is a linear data structure characterised by its first-in-first-out (FIFO) behaviour. Queues pop
(remove, 'dequeue'
) the head
(front, first element) of the Queue (i.e 1
is 'dequeued'
from [1,2,3,4,5]
) and append
(add, put, 'enqueue'
) an element at the tail
(back, rear, last element) of the Queue. Queues are fixed sized, meaning an object cannot be enqueued if the Queue is full.
q = Queue([1,2,3,4,5])
print(q)
[1,2,3,4,5]
Size: 6 (one more than the length of the Queue)
q.enqueue(6)
print(q)
[1,2,3,4,5,6]
q.dequeue() # no args since it will always remove the head of the Queue
print(q)
[2,3,4,5,6]
Removed: 1 (previous head)
New head: 2
q.enqueue(7)
[2,3,4,5,6,7]
q.enqueue(8)
raise QueueFullError("Cannot enqueue at full size: 6")
Queue(items: object = None, size: int = None)
- Optional parameters:items
(the items in the queue) andsize
(the size allocated for the queue)
items
- the queue itself, more specifically its items, constructed as a listsize
- the size of the queuehead
- the first element of the queue, i.eself.items[0]
tail
- the last element of the queue, i.eself.items[-1]
enqueue(item: object)
- appends anobject
to the end of the queue; extends the queue ifobject
is of typelist
dequeue()
- removes thehead
of the queue (self.items.pop(0)
)peek()
- equivalent tohead
attributeclear()
- empties the queuemerge(queue: 'Queue')
- merges two queues together viaenqueue()
methodfrequency(item: object)
- returns the amount of times (frequency) an item is present in a queuecopy()
- creates a copy of current queue and returns itis_full()
- returns aTrue
if queue is fullis_empty()
- returnsTrue
if queue is emptyavailable_size()
- subtracts the length of the queue by thesize
attribute to calculate the available size remaining in the queuesort()
- sorts the queue in ascending order
QueueFullError()
- Raised when attempting to enqueue a full Queue, exceeding its fixed sizeQueueEmptyError()
- Raised when attempting to dequeue an empty QueueQueueError()
- Raised when ran into esoteric errors, such as trying to enqueue 2D arrays