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
| Operation | What it does | Time |
|---|---|---|
enqueue(x) | Add x at the rear | O(1) |
dequeue() | Remove and return the front element | O(1) |
peek() / front() | Return the front element without removing it | O(1) |
isEmpty() / isFull() | Check before dequeue / enqueue | O(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
frontis the index of the first element andrearthe index of the last. Both start at −1 (empty).enqueueadds at++rear. The first time, it also setsfront = 0.dequeuereturnsqueue[front]and movesfrontforward. Elements are not shifted, so it stays O(1).- 10 and 20 come out first, in the same order they went in: FIFO.
- Look at the end: only 2 elements (30, 40) are stored, but adding 50 gives overflow. Indexes 0 and 1 are free, yet
rearalready 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
| Point | Stack | Queue |
|---|---|---|
| Principle | LIFO | FIFO |
| Ends used | One (top) | Two (front and rear) |
| Insert / delete | push / pop | enqueue / dequeue |
| Real example | Pile of plates, undo | Ticket 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) andrear(add here). Both operations are O(1). - When the last node is removed,
rearmust 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
mallocfails. - 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 whenrear == 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
| Mistake | What happens | Fix |
|---|---|---|
| Deleting from the rear | It becomes a stack, not a queue | Delete from the front |
| Shifting all elements on every dequeue | O(n) dequeue, slow | Move front, or use a circular queue |
| Not resetting rear when the list queue becomes empty | rear points to freed memory | if (front == NULL) rear = NULL; |
Forgetting front = 0 on the first enqueue | front stays −1; queue looks empty | Set front when the first element arrives |
| Assuming "rear == SIZE − 1" means no free space | Overflow while slots are empty | Use a circular queue |
Queue Practice Questions
- What is a queue? Why is it called FIFO?
- What are front and rear?
- Explain the wasted-space problem of a linear array queue.
- Write the steps of enqueue in a linked-list queue.
- Give four applications of queues.
Show answers
- A linear structure with insertion at the rear and deletion at the front; the first element inserted is the first removed.
- front is the position of the next element to be removed; rear is the position of the last element added.
- 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.
- Create a node with next = NULL; if the queue is empty, front = rear = node; otherwise rear→next = node and rear = node.
- 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)
-
A queue follows:
A) LIFO B) FIFO C) Priority order D) Random
-
In a queue, deletion happens at the:
A) Rear B) Front C) Middle D) Top
-
Enqueue 5, 6, 7, then dequeue once. The front element is:
A) 5 B) 6 C) 7 D) Empty
-
The wasted-space problem occurs in a:
A) Linked-list queue B) Linear array queue C) Stack D) Circular queue
-
Which is a typical use of a queue?
A) Undo operation B) Printer job scheduling C) Bracket matching D) Recursion
Show answers
- B: FIFO.
- B: front.
- B: 6.
- B: a linear array queue.
- B: printer job scheduling.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Queue | FIFO: rear in, front out |
|---|---|
| Operations | enqueue, dequeue, peek: O(1) |
| Array empty | front == −1 || front > rear |
| Array full | rear == SIZE − 1 |
| Problem | Linear array queue wastes space |
| Fix | Circular queue or linked list |
| Uses | Printer, 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.