Algorithms

Queue (data structure): first come, first served

Cover of the article Queue (data structure): first come, first served
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does a queue work?
  2. What’s the difference between a queue and a stack?
  3. Queue in PHP, Python, C and Java
  4. Now you ask: can’t I just use an array as a queue?
  5. Where do queues show up in everyday life?
  6. Now it’s your turn!

Queue is a data structure in which the first element that goes in is the first one that comes out. This behavior has a name: FIFO, short for First In, First Out.

In the article on the linked list, I left you a challenge: create a method that counts how many nodes the list has. Did you manage? Here’s mine, in Python:

class Node:
    def __init__(self, value, next_node=None):
        self.value = value
        self.next = next_node


class SinglyLinkedList:
    def __init__(self):
        self.head = None

    def add_first(self, value):
        self.head = Node(value, self.head)

    def count(self):
        total = 0
        current = self.head

        while current is not None:
            total += 1  # instead of showing the value, add one
            current = current.next

        return total


tasks = SinglyLinkedList()
tasks.add_first("Study")
tasks.add_first("Have lunch")
tasks.add_first("Wake up")

print(tasks.count())  # 3

The only difference from traverse is that, instead of showing each node’s value, the method adds one. If yours turned out different and it works, congratulations: in programming, there’s almost always more than one right way!

How does a queue work?

Think of the line at the bakery. Whoever arrives joins at the back. Whoever is served leaves from the front. Nobody gets in the middle, and nobody is served before whoever arrived first (at least, nobody should haha).

Three-panel comic strip in the bakery line: Carla arrives and joins at the back, Ana, the first in line, is served and leaves, and Davi is sent to the back of the line
The bakery line: you join at the back, leave from the front, and nobody cuts in.

A queue has two main operations:

  • Enqueue: puts an element at the back of the queue.
  • Dequeue: takes out the element at the front of the queue.

Here’s the step by step:

StepOperationQueue (front to back)Who left
1Enqueue AnaAnaNobody
2Enqueue BrunoAna, BrunoNobody
3Enqueue CarlaAna, Bruno, CarlaNobody
4DequeueBruno, CarlaAna
5DequeueCarlaBruno
A queue step by step: whoever arrived first leaves first.
See the queue animation, step by step
Animation of a queue in which Ana, Bruno and Carla join at the back, and then Ana and Bruno leave from the front, in the order they arrived
The same step by step in motion: three arrivals at the back and two departures from the front.

What’s the difference between a queue and a stack?

Do you already know the stack? Both keep elements in sequence, but the exit rule of one is the opposite of the other:

QueueStack
RuleFIFO: the first one in is the first one outLIFO: the last one in is the first one out
Where it goes inAt the backAt the top
Where it comes outFrom the frontFrom the top
AnalogyBakery lineStack of plates
The difference between a queue and a stack.
Diagram comparing a queue and a stack with Ana, Bruno and Carla: in the queue, Ana leaves; in the stack, Carla leaves
Same order of arrival, different exits: in the queue, whoever arrived first leaves; in the stack, whoever arrived last leaves.

Queue in PHP, Python, C and Java

Let’s use what you learned in the previous article: our queue will be a linked list that keeps two references, one to the front and another to the back. That way, joining at the back and leaving from the front take the same work, no matter how long the queue is. Here it is in PHP:

<?php

class Node
{
    public function __construct(
        public string $value,
        public ?Node $next = null,
    ) {
    }
}

class Queue
{
    private ?Node $front = null;
    private ?Node $back = null;

    public function enqueue(string $value): void
    {
        $newNode = new Node($value);

        if ($this->back === null) {
            $this->front = $newNode; // empty queue: the new node is the first one
        } else {
            $this->back->next = $newNode; // the last node now points to the new one
        }

        $this->back = $newNode;
    }

    public function dequeue(): ?string
    {
        if ($this->front === null) {
            return null; // empty queue: there's nobody to serve
        }

        $value = $this->front->value;
        $this->front = $this->front->next; // the second one becomes the first

        if ($this->front === null) {
            $this->back = null; // the last one left: the queue is empty
        }

        return $value;
    }
}

$queue = new Queue();
$queue->enqueue('Ana');
$queue->enqueue('Bruno');
$queue->enqueue('Carla');

echo $queue->dequeue(), PHP_EOL; // Ana
echo $queue->dequeue(), PHP_EOL; // Bruno

In Python:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


class Queue:
    def __init__(self):
        self.front = None
        self.back = None

    def enqueue(self, value):
        new_node = Node(value)

        if self.back is None:
            self.front = new_node  # empty queue: the new node is the first one
        else:
            self.back.next = new_node  # the last node now points to the new one

        self.back = new_node

    def dequeue(self):
        if self.front is None:
            return None  # empty queue: there's nobody to serve

        value = self.front.value
        self.front = self.front.next  # the second one becomes the first

        if self.front is None:
            self.back = None  # the last one left: the queue is empty

        return value


queue = Queue()
queue.enqueue("Ana")
queue.enqueue("Bruno")
queue.enqueue("Carla")

print(queue.dequeue())  # Ana
print(queue.dequeue())  # Bruno

And in C:

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

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

struct Queue {
    struct Node *front;
    struct Node *back;
};

void enqueue(struct Queue *queue, int value) {
    struct Node *new_node = malloc(sizeof(struct Node));

    if (new_node == NULL) {
        return; // out of memory: the queue stays as it was
    }

    new_node->value = value;
    new_node->next = NULL;

    if (queue->back == NULL) {
        queue->front = new_node; // empty queue: the new node is the first one
    } else {
        queue->back->next = new_node; // the last node now points to the new one
    }

    queue->back = new_node;
}

int dequeue(struct Queue *queue) {
    if (queue->front == NULL) {
        return -1; // empty queue: there's nobody to serve
    }

    struct Node *first = queue->front;
    int value = first->value;

    queue->front = first->next; // the second one becomes the first

    if (queue->front == NULL) {
        queue->back = NULL; // the last one left: the queue is empty
    }

    free(first);
    return value;
}

int main(void) {
    struct Queue queue = {NULL, NULL};

    enqueue(&queue, 101);
    enqueue(&queue, 102);
    enqueue(&queue, 103);

    printf("%d\n", dequeue(&queue)); // 101
    printf("%d\n", dequeue(&queue)); // 102
    printf("%d\n", dequeue(&queue)); // 103
    return 0;
}

And in Java:

public class QueueByHand {
    static class Node {
        String value;
        Node next;

        Node(String value) {
            this.value = value;
        }
    }

    static class Queue {
        private Node front = null;
        private Node back = null;

        void enqueue(String value) {
            Node newNode = new Node(value);
            if (back == null) {
                front = newNode; // empty queue: the new node is the first one
            } else {
                back.next = newNode; // the last node now points to the new one
            }
            back = newNode;
        }

        String dequeue() {
            if (front == null) {
                return null; // empty queue: there's nobody to serve
            }
            String value = front.value;
            front = front.next; // the second one becomes the first
            if (front == null) {
                back = null; // the last one left: the queue is empty
            }
            return value;
        }
    }

    public static void main(String[] args) {
        Queue queue = new Queue();
        queue.enqueue("Ana");
        queue.enqueue("Bruno");
        queue.enqueue("Carla");
        System.out.println(queue.dequeue()); // Ana
        System.out.println(queue.dequeue()); // Bruno
    }
}

Notice two precautions that show up in all four languages. When the queue is empty, the first one to arrive is both the front and the back. And when the last one leaves, the back also has to point to “nothing” again. Forgetting these two details is a very common mistake, so I’ll say it again: an empty queue needs attention on the way in and on the way out!

In the C example, I used ticket numbers instead of names, and -1 signals that the queue is empty.

Now you ask: can’t I just use an array as a queue?

You can, but there’s a cost: taking the first value out of an array forces all the others to move one position forward. The Python tutorial itself recommends, for queues, the collections.deque class, which was designed to add and remove efficiently at both ends:

from collections import deque

queue = deque()
queue.append("Ana")
queue.append("Bruno")

print(queue.popleft())  # Ana

PHP also comes with a ready-made queue, the SplQueue class, which uses a doubly linked list under the hood:

<?php

$queue = new SplQueue();
$queue->enqueue('Ana');
$queue->enqueue('Bruno');

echo $queue->dequeue(), PHP_EOL; // Ana

In Java, the ready-made queue is the Queue interface. One of the classes that work as a queue is ArrayDeque: add puts an element at the back, and poll takes one from the front.

import java.util.ArrayDeque;
import java.util.Queue;

public class BuiltInQueue {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();
        queue.add("Ana");
        queue.add("Bruno");
        System.out.println(queue.poll()); // Ana
    }
}

In everyday work, you’ll use these ready-made structures. But now you know what happens inside them, and that’s what separates those who understand from those who just memorize!

Where do queues show up in everyday life?

  • Print queue: documents come out in the order they were sent.
  • Customer service: tickets at the bank, support requests, orders at a snack bar.
  • Background tasks: a website that needs to send thousands of emails puts each one in a queue and processes them one by one.

Now it’s your turn!

Add a peek method to your queue: it shows who’s first in line without removing anyone. Before typing, think: what should it return when the queue is empty?

Try it on your own first! You’ve already seen harder things than this in this article. I’ll tell you the answer in the next one.

So far, all the structures we’ve seen were “in a line”: one element after another. In the next article, that changes: you’ll meet the binary tree, in which each node can point to two paths. See you there!

Stay confident!!!

Sources:

  • Python documentation. Data Structures: Using Lists as Queues, with the list that isn’t efficient as a queue, because removing from the beginning shifts all the other elements, and collections.deque, designed for fast appends and pops from both ends.
  • PHP Manual. The SplQueue class, with a queue implemented using a doubly linked list.
  • Oracle, Java 21 documentation. ArrayDeque class, with add, which inserts at the end, and poll, which retrieves and removes the head of the queue, or returns null when it’s empty.
  • Virginia Tech, OpenDSA. Linked Queues, with the linked queue as an adaptation of the linked list, pointers to the front and rear nodes, and the comparison in which every operation takes constant time.
  • Aalto University, OpenDSA (CS-A1141). Queues, with insertion only at the back (enqueue), removal only at the front (dequeue) and the array-based queue with a circular increment.
  • Brad Miller and David Ranum, Problem Solving with Algorithms and Data Structures using Python. The Queue Abstract Data Type, with items added at the rear and removed from the front in FIFO order, and What Is a Queue?, with print tasks that get in line.
  • Cory Althoff, The Self-Taught Computer Scientist. Chapter 12: Queues, with the checkout line at a grocery store and the two main operations: enqueueing at the rear and dequeueing from the front.
  • University of Ottawa, ITI1121. LinkedQueue, with queues as FIFOs, enqueue at the rear, dequeue at the front and the queue built with linked elements (PDF).
  • James Madison University, CS 240 (Nathan Sprague). Queues, with the cost of each operation and a linked queue that needs both a head and a tail reference.
  • Kansas State University, CC 310. What is a Queue?, with the line to get into a ballgame, movie or concert, and data that goes in at the rear and comes out at the front.
  • IIT Kanpur, MTH409 (S. Ghorai). C programming: queues, with a queue in C that keeps pointers to the front and to the back (PDF).
  • The examples were run on PHP 8.3, Python 3.13, GCC 13 and Java 21.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).