A "queue," like a "stack," is an ordered collection of items. Items can be "queued" onto the end of the queue, in order, with items queued later being placed behind items that have arrived earlier. When items are removed from the queue they are "dequeued" from the front in a "first come, first served" fashion. The item at the front of the queue can be "peeked" at (identified without removing it from the queue), and the "size" of the queue can be identified at any time. Also, the queue can be identified as being "empty" (a size of 0).
Real-life examples of queues can be found everywhere: Waiting in line to get into a movie, lining up to be served at a fast-food restaurant, etc. Because of the way items are queued and dequeued in a queue, it is sometimes called a First In-First Out (FIFO) structure.
Write a Python class Queue
that implements this abstract data type using a list
. The Queue
class will include:
enqueue(item)
method to place an item onto the back of the queuedequeue()
method to remove an item from the front of the queue, and return that removed item as a resultpeek()
method which returns the value of the item at the front of the queue without removing itsize()
method which returns the number of items in the queueis_empty()
method which returns True
or False
, depending on the state of the queueThe Abstract Data Type Queue has been described, but how should it best be implemented, given that we're writing it in Python? Consider the following list of items:
Value | 3 | 7 | 14 | -5 | 3 | 10 |
------+-----+-----+-----+-----+-----+-----+
Index | 0 | 1 | 2 | 3 | 4 | 5 |
As we consider the tasks that our Queue
class will be performing, will it be a better choice to have the tail (where new items are added) at the left and the head (where old items are removed) on the left side (at index 0) or on the right side (at index -1) ?
To be clear, either strategy can be applied here. However, one will be more efficient than the other, based on the technical implementations and design decisions of Python. Which strategy is better: the tail at index 0 or the head at index 0?
Implement the Queue
class using both strategies listed in the Notes above to identify which strategy is more efficient in Python.