Skip to content
StudyFame

Queue in C

A queue works like the line at a railway ticket counter: people join at the back and are served from the front. The first person in line is the first person served. This rule is called FIFO (First In, First Out).

In this lesson you will build a queue with an array and with a linked list, write enqueue and dequeue, handle overflow and underflow, see why a simple array queue wastes space, and learn where queues are used.

What You Will Learn

  • The FIFO principle and the front and rear of a queue.
  • Queue operations: enqueue, dequeue, peek, isEmpty, isFull.
  • How to implement a queue with an array.
  • The wasted-space problem of a linear array queue.
  • How to implement a queue with a linked list.
  • Stack vs queue, and real uses of queues.

Queue in C Explained

Exam definition: A queue is a linear data structure in which elements are inserted at one end, called the rear, and deleted from the other end, called the front. It follows the FIFO (First In, First Out) principle. Insertion is called enqueue and deletion is called dequeue. Enqueue on a full queue causes overflow; dequeue on an empty queue causes underflow.

Memory trick: A queue is the line at a ticket counter. New people join at the rear (enqueue); the clerk serves the person at the front (dequeue). Nobody jumps the line. A stack is the opposite: like plates, the newest one leaves first.

enqueue 10, 20, 30                  dequeue -> 10

front              rear              front        rear
  │                 │                  │           │
  ▼                 ▼                  ▼           ▼
[ 10 ][ 20 ][ 30 ][    ]       [    ][ 20 ][ 30 ][    ]

Syntax: Queue Operations

OperationWhat it doesTime
enqueue(x)Add x at the rearO(1)
dequeue()Remove and return the front elementO(1)
peek() / front()Return the front element without removing itO(1)
isEmpty() / isFull()Check before dequeue / enqueueO(1)
#define SIZE 5
int queue[SIZE];
int front = -1, rear = -1;       /* both -1: empty queue */

/* enqueue */ if (rear == SIZE - 1) overflow; else { if (front == -1) front = 0; queue[++rear] = x; }
/* dequeue */ if (front == -1 || front > rear) underflow; else x = queue[front++];

Example 1: Queue Using an Array

#include <stdio.h>

#define SIZE 4

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

int is_empty(void) { return front == -1 || front > rear; }
int is_full(void)  { return rear == SIZE - 1; }

void enqueue(int x)
{
    if (is_full())
    {
        printf("Overflow! cannot add %d\n", x);
        return;
    }
    if (front == -1)
        front = 0;
    queue[++rear] = x;
    printf("Enqueued %d\n", x);
}

int dequeue(void)
{
    if (is_empty())
    {
        printf("Underflow! queue is empty\n");
        return -1;
    }
    return queue[front++];
}

void display(void)
{
    int i;
    if (is_empty())
    {
        printf("Queue: (empty)\n");
        return;
    }
    printf("Queue (front to rear): ");
    for (i = front; i <= rear; i++)
        printf("%d ", queue[i]);
    printf("\n");
}

int main(void)
{
    enqueue(10);
    enqueue(20);
    enqueue(30);
    display();
    printf("Dequeued %d\n", dequeue());
    printf("Dequeued %d\n", dequeue());
    display();
    enqueue(40);
    enqueue(50);                 /* rear is at the end: "full" */
    printf("front = %d, rear = %d\n", front, rear);
    return 0;
}

Output

Enqueued 10
Enqueued 20
Enqueued 30
Queue (front to rear): 10 20 30
Dequeued 10
Dequeued 20
Queue (front to rear): 30
Enqueued 40
Overflow! cannot add 50
front = 2, rear = 3

Code Explanation

  1. front is the index of the first element and rear the index of the last. Both start at −1 (empty).
  2. enqueue adds at ++rear. The first time, it also sets front = 0.
  3. dequeue returns queue[front] and moves front forward. Elements are not shifted, so it stays O(1).
  4. 10 and 20 come out first, in the same order they went in: FIFO.
  5. Look at the end: only 2 elements (30, 40) are stored, but adding 50 gives overflow. Indexes 0 and 1 are free, yet rear already reached the last index. This is the wasted-space problem of a linear array queue.

How the Wasted-Space Problem Happens

After dequeue, dequeue, enqueue 40:

index:   0      1      2      3
       [free] [free] [ 30 ] [ 40 ]
                      front   rear = SIZE-1   ->  "full", but 2 slots are empty!

There are two fixes: shift all elements left after each dequeue (O(n), slow), or let the indexes wrap around to 0. The second idea is the circular queue, covered in the next lesson. A linked-list queue avoids the problem completely.

Stack vs queue

PointStackQueue
PrincipleLIFOFIFO
Ends usedOne (top)Two (front and rear)
Insert / deletepush / popenqueue / dequeue
Real examplePile of plates, undoTicket line, printer jobs

Example 2: Queue Using a Linked List

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

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

struct queue
{
    struct node *front;      /* delete here */
    struct node *rear;       /* insert here */
};

void enqueue(struct queue *q, int x)
{
    struct node *n = malloc(sizeof *n);
    if (n == NULL)
        exit(1);
    n->data = x;
    n->next = NULL;
    if (q->rear == NULL)
        q->front = q->rear = n;      /* first element */
    else
    {
        q->rear->next = n;
        q->rear = n;
    }
}

int dequeue(struct queue *q, int *x)
{
    struct node *t = q->front;
    if (t == NULL)
        return 0;                    /* underflow */
    *x = t->data;
    q->front = t->next;
    if (q->front == NULL)
        q->rear = NULL;              /* queue became empty */
    free(t);
    return 1;
}

void display(const struct queue *q)
{
    const struct node *p;
    printf("Queue: ");
    for (p = q->front; p != NULL; p = p->next)
        printf("%d ", p->data);
    printf("\n");
}

int main(void)
{
    struct queue q = {NULL, NULL};
    int x, i;

    for (i = 1; i <= 5; i++)
        enqueue(&q, i * 100);
    display(&q);

    dequeue(&q, &x);
    printf("Served %d\n", x);
    dequeue(&q, &x);
    printf("Served %d\n", x);
    enqueue(&q, 600);
    display(&q);

    while (dequeue(&q, &x))
        printf("Served %d\n", x);
    printf("Empty now? %s\n", q.front == NULL ? "yes" : "no");
    return 0;
}

Output

Queue: 100 200 300 400 500
Served 100
Served 200
Queue: 300 400 500 600
Served 300
Served 400
Served 500
Served 600
Empty now? yes
  • The queue keeps two pointers: front (remove here) and rear (add here). Both operations are O(1).
  • When the last node is removed, rear must also become NULL; otherwise it would point to freed memory.
  • There is no fixed size, so no wasted-space problem; the only "overflow" is when malloc fails.
  • The while (dequeue(...)) loop empties the queue and frees every node.

Important Points to Remember

  • Queue = FIFO: insert at the rear, delete from the front.
  • Operations: enqueue, dequeue, peek, all O(1).
  • Array queue: empty when front == -1 || front > rear; full when rear == SIZE - 1.
  • A linear array queue wastes space after dequeues; use a circular queue or a linked list.
  • Linked-list queue: keep front and rear pointers; reset rear when the queue empties.
  • Uses: printer spooling, CPU/process scheduling, keyboard buffer, BFS in graphs, call centres.

Common Mistakes Beginners Make

MistakeWhat happensFix
Deleting from the rearIt becomes a stack, not a queueDelete from the front
Shifting all elements on every dequeueO(n) dequeue, slowMove front, or use a circular queue
Not resetting rear when the list queue becomes emptyrear points to freed memoryif (front == NULL) rear = NULL;
Forgetting front = 0 on the first enqueuefront stays −1; queue looks emptySet front when the first element arrives
Assuming "rear == SIZE − 1" means no free spaceOverflow while slots are emptyUse a circular queue

Queue Practice Questions

  1. What is a queue? Why is it called FIFO?
  2. What are front and rear?
  3. Explain the wasted-space problem of a linear array queue.
  4. Write the steps of enqueue in a linked-list queue.
  5. Give four applications of queues.
Show answers
  1. A linear structure with insertion at the rear and deletion at the front; the first element inserted is the first removed.
  2. front is the position of the next element to be removed; rear is the position of the last element added.
  3. After dequeues, front moves right and the freed slots at the beginning can't be reused, so the queue reports full when rear reaches the end even though space is free.
  4. Create a node with next = NULL; if the queue is empty, front = rear = node; otherwise rear→next = node and rear = node.
  5. Printer spooling, CPU scheduling, keyboard/IO buffers, breadth-first search, customer service systems.

Coding Exercise

Simulate a ticket counter with a linked-list queue of customer names (use a char name[20] in each node). Add Asha, Ravi, Meena and Arjun, serve two customers, add Kiran, then print who is still waiting.

Show solution
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node
{
    char name[20];
    struct node *next;
};

struct queue
{
    struct node *front, *rear;
};

void join(struct queue *q, const char *name)
{
    struct node *n = malloc(sizeof *n);
    if (n == NULL)
        exit(1);
    strcpy(n->name, name);
    n->next = NULL;
    if (q->rear) q->rear->next = n; else q->front = n;
    q->rear = n;
}

void serve(struct queue *q)
{
    struct node *t = q->front;
    if (t == NULL)
        return;
    printf("Serving %s\n", t->name);
    q->front = t->next;
    if (q->front == NULL)
        q->rear = NULL;
    free(t);
}

int main(void)
{
    struct queue q = {NULL, NULL};
    struct node *p;

    join(&q, "Asha");
    join(&q, "Ravi");
    join(&q, "Meena");
    join(&q, "Arjun");
    serve(&q);
    serve(&q);
    join(&q, "Kiran");

    printf("Still waiting: ");
    for (p = q.front; p != NULL; p = p->next)
        printf("%s ", p->name);
    printf("\n");

    while (q.front != NULL)
    {
        p = q.front;
        q.front = p->next;
        free(p);
    }
    return 0;
}
Serving Asha
Serving Ravi
Still waiting: Meena Arjun Kiran 

Quick Quiz: Queue in C (MCQ)

  1. A queue follows:

    A) LIFO   B) FIFO   C) Priority order   D) Random

  2. In a queue, deletion happens at the:

    A) Rear   B) Front   C) Middle   D) Top

  3. Enqueue 5, 6, 7, then dequeue once. The front element is:

    A) 5   B) 6   C) 7   D) Empty

  4. The wasted-space problem occurs in a:

    A) Linked-list queue   B) Linear array queue   C) Stack   D) Circular queue

  5. Which is a typical use of a queue?

    A) Undo operation   B) Printer job scheduling   C) Bracket matching   D) Recursion

Show answers
  1. B: FIFO.
  2. B: front.
  3. B: 6.
  4. B: a linear array queue.
  5. B: printer job scheduling.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

QueueFIFO: rear in, front out
Operationsenqueue, dequeue, peek: O(1)
Array emptyfront == −1 || front > rear
Array fullrear == SIZE − 1
ProblemLinear array queue wastes space
FixCircular queue or linked list
UsesPrinter, CPU scheduling, BFS, buffers

Frequently asked questions

What is a queue in data structures?
A linear structure where elements are added at the rear and removed from the front, following FIFO.
What is the difference between a stack and a queue?
A stack is LIFO with one end (top); a queue is FIFO with two ends (front and rear).
Why is a circular queue better than a linear queue?
It reuses the free slots at the beginning by wrapping indexes around, so no space is wasted.

Remember

  • Queue = ticket line: join at the back, leave from the front.
  • Array queue wastes space; circular queue fixes it.

Next Topic

Next lesson: Circular Queue in C. You will make the array queue wrap around with the modulo operator, so no space is wasted.