Course contentsShow
← C
Lesson 1020 of 1,21914. Data Structures in CFree lesson

Linked list queue implementation

Linked list queue implementation

What you'll learn: How to build a flexible Queue using a linked list to avoid the fixed-size limitations of arrays.

The "Growing Line" analogy

Think of a linked list queue like a line of people waiting for coffee. Unlike an array queue—which is like a bench with exactly five seats—a linked list queue is like a line standing in an open hallway. If a sixth person arrives, they simply stand behind the fifth person. There is no physical limit to how long the line can get, as long as the building (your computer's memory) has space.

The Two-Pointer strategy

To manage this line efficiently, we don't just track the start; we track both ends.

  1. Front: The person currently being served (where we dequeue).
  2. Rear: The last person to join (where we enqueue).

By keeping a Rear pointer, we don't have to walk through the entire line to find the end every time someone new joins. We just plug them in right behind the current Rear and update the pointer.

Implementation in C

In this approach, each "person" in line is a Node containing data and a pointer to the next person.

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

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

struct Queue {
    struct Node *front, *rear;
};

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

    // If queue is empty, new node is both front and rear
    if (q->rear == NULL) {
        q->front = q->rear = newNode;
        return;
    }

    // Add the new node at the end and update rear
    q->rear->next = newNode;
    q->rear = newNode;
}

int dequeue(struct Queue* q) {
    if (q->front == NULL) return -1; // Queue is empty

    struct Node* temp = q->front;
    int data = temp->data;

    q->front = q->front->next;

    // If front becomes NULL, rear must also be NULL
    if (q->front == NULL) q->rear = NULL;

    free(temp);
    return data;
}

Why use this?

While arrays are simple, they require you to know the maximum size upfront. If you guess too small, your program crashes; if you guess too large, you waste memory. A linked list queue is dynamic—it grows and shrinks perfectly to fit your data, making it the go-to choice for systems where the workload is unpredictable.

Key takeaway

A linked list queue uses front and rear pointers to provide efficient, O(1) additions and removals without ever running out of "slots."