Queue
Queue operations in Python
Write enqueue, dequeue, isEmpty, size and peek.
A queue has two main operations:
- ENQUEUE: insert an element at the REAR. Inserting into a full queue causes overflow.
- DEQUEUE: remove the element at the FRONT. Removing from an empty queue causes underflow.
Supporting operations:
- IS EMPTY: check whether the queue is empty, to avoid underflow.
- PEEK: look at the front element without removing it.
- IS FULL: check whether the queue is full, to avoid overflow.
In Python, a list works as a queue, with the left end as the FRONT and the right end as the REAR:
- myQueue = list() creates an empty queue.
- enqueue uses append(element), adding at the rear.
- dequeue uses pop(0), removing the element at index 0, the front.
- size() uses len().
- peek() returns myQueue[0], the front element.
IS FULL is not needed in Python, because a list has no fixed size: it simply grows as elements are added.
For example, with the queue [P1, P2]: dequeue removes P1 from the front, leaving [P2]; then enqueue P3 adds it at the rear, giving [P2, P3].
append() to enqueue; pop(0) to dequeue.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.