A queue follows First In First Out (FIFO): the item that goes in first is the item that comes out first. Putting items in is called enqueue; removing items is called dequeue.
Basic Operations
A queue is an abstract data structure (ADT) that supports:
- Enqueue — add an element to the end of the queue.
- Dequeue — remove an element from the front of the queue.
- IsEmpty — check if the queue is empty.
- IsFull — check if the queue is full.
- Peek — get the value at the front without removing it.
Working of a Queue
- Two pointers,
FRONTandREAR, are used. FRONTtracks the first element of the queue.REARtracks the last element of the queue.- Initially, both
FRONTandREARare set to-1.
Enqueue
- Check if the queue is full.
- For the first element, set
FRONTto0. - Increase the
REARindex by 1. - Add the new element at the position pointed to by
REAR.
Dequeue
- Check if the queue is empty.
- Return the value pointed to by
FRONT. - Increase the
FRONTindex by 1. - For the last element, reset
FRONTandREARto-1.
Complexity
Enqueue and dequeue on an array-backed queue are O(1). If you use pop(n) in Python, the
complexity can be O(n) depending on the position of the item being popped.