πͺ Queue in DSA
A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. The first element added to the queue will be the first to be removed. It is often used in scenarios like task scheduling, printer queues, and resource allocation.
Basic Operations of Queue
The following are the basic operations performed on a queue:
- Enqueue: Adds an element to the rear (end) of the queue.
- Dequeue: Removes an element from the front of the queue.
- Peek (Front): Returns the element at the front of the queue without removing it.
- isEmpty: Checks if the queue is empty.
- isFull: Checks if the queue is full (in case of a fixed-size queue).
Types of Queues
There are several types of queues based on how the operations are performed:
- Simple Queue: A basic FIFO queue.
- Circular Queue: A queue where the last position is connected back to the first, allowing better utilization of space.
- Priority Queue: A queue where each element has a priority, and elements are dequeued based on priority.
- Double-Ended Queue (Deque): A queue where elements can be added or removed from both ends.
Queue Implementation
A queue can be implemented using an array or a linked list. Hereβs an example of a simple queue implemented using an array:
#include
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
void enqueue(int value) {
if (rear == MAX - 1) {
printf("Queue is Full\n");
} else {
if (front == -1) front = 0;
rear++;
queue[rear] = value;
printf("Enqueued %d\n", value);
}
}
int dequeue() {
if (front == -1 || front > rear) {
printf("Queue is Empty\n");
return -1;
} else {
int dequeued = queue[front];
front++;
return dequeued;
}
}
int peek() {
if (front == -1 || front > rear) {
printf("Queue is Empty\n");
return -1;
} else {
return queue[front];
}
}
int isEmpty() {
return (front == -1 || front > rear);
}
int main() {
enqueue(10);
enqueue(20);
enqueue(30);
printf("Dequeued: %d\n", dequeue());
printf("Front: %d\n", peek());
return 0;
}
Applications of Queue
Queues are widely used in various applications, including:
- Job Scheduling: Operating systems use queues for job scheduling where jobs are processed in the order they arrive.
- Printer Queues: Print jobs are added to a queue and processed one at a time.
- Call Center Systems: Calls are queued and processed in order of arrival.
- Data Buffering: Queues are used for managing the buffer in streams of data (e.g., video streaming).
π Advantages of Queues:
- Efficient processing of elements in a FIFO manner.
- Essential for managing resources and tasks with order.
- Provides flexibility with different types like circular queues, priority queues, etc.
π Try Implementing Queue Operations:
- Implement a priority queue and see how elements are dequeued based on priority.
- Experiment with circular queues to understand how they work better than regular queues.
- Create a deque and explore how elements can be added/removed from both ends.