Queue - Everything You Need to Know
What is a Queue?
A queue is a linear data structure that follows the FIFO (First In, First Out) principle. This means that the element added first will be the first one to be removed, similar to a queue in real life (like waiting in line for a ticket).
Front and Rear in a Queue
- Front: The index where elements are removed from the queue.
- Rear: The index where new elements are inserted into the queue.
- When the queue is empty, both front and rear are set to
-1.
- When an element is added, the rear moves forward.
- When an element is removed, the front moves forward.
Enqueue (Insertion in Queue)
- When adding an element, we insert it at the rear position.
- If the queue is empty, both front and rear are set to
0.
- The rear pointer increases by
1 with each new element.
- If
rear reaches the max size of the queue, it causes a Queue Overflow (meaning no more elements can be added).
🔹 Dequeue (Removing an Element from Queue)
- The element at the front is removed.
- The front pointer moves forward by
1.
- If
front > rear, the queue is empty, causing Queue Underflow (no elements left to remove).
- In a regular queue, removed elements leave empty spaces, reducing efficiency. Circular queues solve this issue.