DATA STRUCTURES PROGRAM • QUEUES & DEQUES

Implement a Queue Using a Linked List

Learn how to implement a queue using a linked list using a clear C program.

BeginnerQueueFIFOfront/rear

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Removed = 10
Front = 20

COMPLETE C PROGRAM

Complete C implementation

dsa-queue-linked-list.c
Open in compiler
#include <stdio.h>
#include <stdlib.h>

struct Node { int data; struct Node *next; };
struct Queue { struct Node *front; struct Node *rear; };
void enqueue(struct Queue *queue, int value)
{
    struct Node *node = malloc(sizeof *node);
    if (node == NULL) exit(EXIT_FAILURE);
    node->data = value; node->next = NULL;
    if (queue->rear == NULL) queue->front = node;
    else queue->rear->next = node;
    queue->rear = node;
}
int dequeue(struct Queue *queue)
{
    if (queue->front == NULL) exit(EXIT_FAILURE);
    struct Node *removed = queue->front; int value = removed->data;
    queue->front = removed->next;
    if (queue->front == NULL) queue->rear = NULL;
    free(removed); return value;
}

int main(void)
{
    struct Queue queue = {NULL, NULL};
    enqueue(&queue, 10); enqueue(&queue, 20); enqueue(&queue, 30);
    printf("Removed = %d\n", dequeue(&queue));
    printf("Front = %d\n", queue.front->data);
    while (queue.front != NULL) dequeue(&queue);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Removed = 10
Front = 20
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Insert through rear and remove through front, resetting rear when the final node leaves.
  3. Display the computed result.

Insert through rear and remove through front, resetting rear when the final node leaves.

EFFICIENCY

Time and space complexity

Time complexity

O(1) per operation

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.