Queues
Queues
What is a queue?
• It is an ordered group of homogeneous items of
elements.
• Queues have two ends:
• Elements are added at one end.
• Elements are removed from the other end.
• The element added first is also removed first (FIFO:
First In, First Out).
Queue Specification
• Definitions: (provided by the user)
• MAX_ITEMS: Max number of items that might be on the
queue
• ItemType: Data type of the items on the queue
• Operations
– MakeEmpty
– Boolean IsEmpty
– Boolean IsFull
– Enqueue (ItemType newItem)
– Dequeue (ItemType& item)
Enqueue (ItemType newItem)
list
collections.deque
queue.Queue
Implementation using
Make front point listelement preceding the front
to the
List element
is a Python’s
in the built-in
queue (onedatamemory
structure that can
location be used
will be
as wasted).
a queue. Instead of enqueue() and dequeue(),
append() and pop() function is used.
Deque is preferred over list in the cases where we need quicker append and
pop operations from both the ends of container, as deque provides an O(1)
time complexity for append and pop operations as compared to list which
provides O(n) time complexity.
Instead of enqueue and deque, append() and popleft() functions are used.
The code uses a deque from the collections module to represent a queue.
It appends ‘a’, ‘b’, and ‘c’ to the queue and dequeues them with q.popleft(),
Queue
resulting is empty
in an empty queue.
now!!
Uncommenting q.popleft() after the queue is empty would raise an IndexError.
•get() – Remove and return an item from the queue. If queue is empty, wait until
an item is available.
•put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
•put_nowait(item) – Put an item into the queue without blocking. If no free slot is
immediately available, raise QueueFull.
Example: This code utilizes the Queue class from the queue
module.
It starts with an empty queue and fills it with ‘a’, ‘b’, and ‘c’.
After dequeuing, the queue becomes empty, and ‘1’ is
added.
# Create a queue
myQueue = Queue()
myQueue.enqueue('A')
myQueue.enqueue('B')
myQueue.enqueue('C')
print("Queue: ", end="")
myQueue.printQueue()
print("Dequeue: ",
myQueue.dequeue())
print("isEmpty: ",
myQueue.isEmpty())