In this article
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).

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:
| Step | Operation | Queue (front to back) | Who left |
|---|---|---|---|
| 1 | Enqueue Ana | Ana | Nobody |
| 2 | Enqueue Bruno | Ana, Bruno | Nobody |
| 3 | Enqueue Carla | Ana, Bruno, Carla | Nobody |
| 4 | Dequeue | Bruno, Carla | Ana |
| 5 | Dequeue | Carla | Bruno |
See the queue animation, step by step

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:
| Queue | Stack | |
|---|---|---|
| Rule | FIFO: the first one in is the first one out | LIFO: the last one in is the first one out |
| Where it goes in | At the back | At the top |
| Where it comes out | From the front | From the top |
| Analogy | Bakery line | Stack of plates |

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, andpoll, which retrieves and removes the head of the queue, or returnsnullwhen 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,
enqueueat the rear,dequeueat 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.

Continue the conversation