A queue is a linear data structure that follows the First In, First Out (FIFO) principle. Elements are added at the rear and removed from the front. It is similar to a queue in a bank or a line at a checkout counter.
Imagine a queue at a ticket counter. The first person to join the queue will be the first to get served, illustrating the FIFO principle.
Consider a queue with elements 1, 2, and 3. The queue looks like this:
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(1);
q.push(2);
q.push(3);
while (!q.empty()) {
std::cout << q.front() << std::endl;
q.pop();
}
return 0;
}
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
queue.add(3);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
from collections import deque
queue = deque()
# Enqueue elements
queue.append(1)
queue.append(2)
queue.append(3)
# Dequeue elements
while queue:
print(queue.popleft())
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct {
int front, rear, size;
int items[MAX];
} Queue;
void enqueue(Queue *q, int item) {
if (q->size < MAX) {
q->items[q->rear] = item;
q->rear = (q->rear + 1) % MAX;
q->size++;
}
}
int dequeue(Queue *q) {
if (q->size > 0) {
int item = q->items[q->front];
q->front = (q->front + 1) % MAX;
q->size--;
return item;
}
return -1; // Empty queue
}
int main() {
Queue q = {0, 0, 0};
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
while (q.size > 0) {
printf("%d\n", dequeue(&q));
}
return 0;
}