What is a Queue?
A queue works exactly like a line of people waiting: whoever joins first at the back gets served first at the front. In data-structure terms, new items go in at the rear through enqueue, and items come out from the front through dequeue, first in, first out.
Enqueue Operation
Enqueue adds an element to the end (rear) of the queue. The front pointer never moves, and the new element becomes the new rear.
↓ enqueue(40) ↓
The new element always goes to the end of the queue.
Dequeue Operation
Dequeue removes and returns the element from the front (head) of the queue. The rear pointer never moves, and whichever element was second in line becomes the new front.
↓ dequeue() → returns 10 ↓
The oldest element (first one added) is always removed first.
Algorithm Steps for Enqueue
- Check if the queue is full (in case of fixed-size implementation)
- If full, return overflow error (or resize in dynamic implementation)
- Increment the rear pointer
- Add the new element at the rear position
Algorithm Steps for Dequeue
- Check if the queue is empty
- If empty, return underflow error
- Access the data at the front of the queue
- Increment the front pointer to the next element
- Return the accessed data
Time Complexity
- Enqueue Operation: O(1) - Constant time to add to the end
- Dequeue Operation: O(1) - Constant time to remove from the front
Space Complexity
The space complexity is O(n) where n is the number of elements in the queue, as it needs to store all elements.
Queues are fundamental in computer science and are used in various applications like CPU scheduling, disk scheduling, handling interrupts, breadth-first search, and any scenario where you need to maintain order of processing.