C Lesson 39 – Queues | Dataplexa

Queues in C

After learning stacks, we now study another important linear data structure called a Queue.

Queues follow a different rule than stacks and are used heavily in real-world systems.


What Is a Queue?

A queue is a linear data structure that follows:

FIFO – First In, First Out

The element inserted first is removed first.


Real-World Example

Think of a queue at a ticket counter:

  • First person in line is served first
  • New people join from the back

This is exactly how a queue works.


Basic Queue Operations

  • Enqueue – Insert an element at the rear
  • Dequeue – Remove an element from the front
  • Front – View the front element

Queue Implementation Using Array


#include <stdio.h>
#define SIZE 5

int queue[SIZE];
int front = -1, rear = -1;

void enqueue(int value) {
    if (rear == SIZE - 1) {
        printf("Queue Overflow\n");
        return;
    }
    if (front == -1)
        front = 0;
    queue[++rear] = value;
}

void dequeue() {
    if (front == -1 || front > rear) {
        printf("Queue Underflow\n");
        return;
    }
    printf("Dequeued: %d\n", queue[front++]);
}

int main() {
    enqueue(10);
    enqueue(20);
    enqueue(30);
    dequeue();
    dequeue();
    return 0;
}

Limitations of Array Queue

  • Fixed size
  • Unused spaces after dequeuing

To overcome this, linked lists are used.


Queue Using Linked List


#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *next;
};

struct Node *front = NULL;
struct Node *rear = NULL;

void enqueue(int value) {
    struct Node *newNode = malloc(sizeof(struct Node));
    newNode->data = value;
    newNode->next = NULL;

    if (rear == NULL) {
        front = rear = newNode;
        return;
    }

    rear->next = newNode;
    rear = newNode;
}

void dequeue() {
    if (front == NULL) {
        printf("Queue Underflow\n");
        return;
    }

    struct Node *temp = front;
    printf("Dequeued: %d\n", temp->data);

    front = front->next;
    if (front == NULL)
        rear = NULL;

    free(temp);
}

int main() {
    enqueue(5);
    enqueue(15);
    enqueue(25);
    dequeue();
    dequeue();
    return 0;
}

Where Queues Are Used

  • CPU scheduling
  • Printer spooling
  • Network traffic
  • Task scheduling

Mini Practice

  • Create a queue using array
  • Implement enqueue and dequeue
  • Display front element

Quick Quiz

Q1. What does FIFO mean?

First In, First Out

Q2. Which operation inserts an element?

Enqueue

Q3. Which operation removes an element?

Dequeue

Q4. Which queue implementation removes size limitation?

Linked list

Q5. Are queues used in operating systems?

Yes