In this article
- How does a linked list work?
- What’s the difference between an array and a linked list?
- How do you build a linked list with just references?
- Now you ask: does next hold a copy of the node?
- How do you add, search and remove nodes?
- Adding at the start: link first, move later
- Adding at the end: walking to the last node
- Searching: traversing until you find it
- Removing: redirecting the arrow
- Now you ask: is a linked list faster than an array?
- What about the other languages?
- Now you ask: do I need to build a linked list by hand?
- What are the most common mistakes with linked lists?
- Now it’s your turn!
Linked list is a data structure in which each element, called a node, holds a value and the information about where the next element is. The nodes don’t need to sit side by side in memory: what keeps the sequence is this link from one to the next.
In the article on bubble sort, I left you a challenge: count the swaps needed to sort the array [4, 2, 7, 1, 3]. The answer is 6 swaps. Did you get it? If your number came out different, redo it pass by pass, without rushing.
Today we start a new track: data structures. And the first question is: if the array already exists, why invent another way to store values in sequence? Hang on, you’ll understand soon!
How does a linked list work?
Think of a treasure hunt. You get the first clue, and it says where the second one is. The second one says where the third one is, and so on, until the last one, which doesn’t point anywhere. You don’t know in advance where the fourth clue is: you have to go through the first, the second and the third to get to it.

A linked list works exactly the same way:
- Node: each clue. It holds a value and the reference to the next node.
- Head: the first clue. It’s the only one the list needs to keep.
- End: the last node, which points to “nothing” (
nullin Java and PHP,Nonein Python andNULLin C).
What’s the difference between an array and a linked list?
In an array, the values sit next to each other, and you can reach any position directly through its index. In a linked list, the nodes are scattered, and you only reach one of them by walking from the head.
| Array | Linked list | |
|---|---|---|
| How the values sit in memory | Side by side | Scattered, connected by references |
| Accessing position 500 | Directly, through the index | You have to go through the 500 nodes that come before it |
| Inserting at the start | You have to push every value one position | You create a node and update one reference |
| Memory per element | Just the value | The value plus the reference to the next node |
So there’s no “best” one: there’s the one that fits the problem. Need to access a lot by index? Array. Need to insert and remove at the start all the time? Linked list. Knowing how to choose is what separates those who memorize from those who understand!
How do you build a linked list with just references?
Let’s get to the code, starting with Java. No ready-made structure from the language: just a class for the node, with two fields. value holds the number. next is of type Node, the node class itself: it’s through it that one object reaches the other.
// Linked list without any ready-made class: just objects connected by references
public class ListByHand {
// each node holds a value and the reference to the next node
static class Node {
int value;
Node next; // nobody gave it a value: it starts as null
Node(int value) {
this.value = value;
}
}
public static void main(String[] args) {
Node first = new Node(10);
Node second = new Node(20);
Node third = new Node(30);
first.next = second; // 10 points to 20
second.next = third; // 20 points to 30
// third.next is still null: it's the end of the list
Node current = first;
while (current != null) {
System.out.print(current.value + " -> ");
current = current.next; // jumps to the next node
}
System.out.println("null");
// under the hood: what does the next field hold?
System.out.println("first.next == second? " + (first.next == second));
second.value = 99;
System.out.println("first.next.value after changing second: " + first.next.value);
}
}
To run it, save the code in a file named ListByHand.java and type java ListByHand.java. Since Java 11, the java command compiles a single-file program in memory and runs the first class in it. Output:
10 -> 20 -> 30 -> null first.next == second? true first.next.value after changing second: 99

The first three lines of main create three separate objects. What turns the three into a list are the two assignments that follow: first.next = second and second.next = third. Nobody touched third.next, and it’s still null: according to the Java specification, every field of an object type starts out as null. That null is what marks the end of the chain.
The while does the treasure hunt: it shows the value of the current node and jumps to where next points, until it reaches null.
Now you ask: does next hold a copy of the node?
No! And the last two lines of the output prove it. With objects, == doesn’t compare the content: according to the Java specification, it’s true when both sides point to the same object. It came out true, so first.next and second are the same object, with two names.
The second proof is even more direct: the program changed the value through the name second and read it through the path first.next. It showed 99. There’s only one object, and both variables hold the path to it. The specification calls this path a reference and explains that it’s a pointer to the object. It’s the same idea as a pointer: the piece of paper with the address, not the house.
How do you add, search and remove nodes?
Linking node by node by hand shows the mechanism, but nobody wants to write first.next = second for every value haha. The SinglyLinkedList class keeps only the head and does the linking inside its methods:
// Hand-made linked list in Java: add, search, remove and traverse
public class SinglyLinkedList {
// each node holds a value and the reference to the next node
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
}
private Node head; // the first node; null while the list is empty
// adds at the start: the new node points to whoever was first
void addFirst(int value) {
Node newNode = new Node(value);
newNode.next = head; // 1st: link the new node to the old first node
head = newNode; // 2nd: the head becomes the new node
}
// adds at the end: walks to the last node and links the new one after it
void addLast(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
// search: goes from node to node until it finds the value or reaches the end
boolean contains(int value) {
Node current = head;
while (current != null) {
if (current.value == value) {
return true;
}
current = current.next;
}
return false;
}
// remove: the previous node now points to the one after the removed node
boolean remove(int value) {
if (head == null) {
return false;
}
if (head.value == value) {
head = head.next;
return true;
}
Node previous = head;
while (previous.next != null && previous.next.value != value) {
previous = previous.next;
}
if (previous.next == null) {
return false; // reached the end without finding it
}
previous.next = previous.next.next; // skips the removed node
return true;
}
// goes from the head to null, showing each link
void traverse() {
Node current = head;
while (current != null) {
System.out.print(current.value + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
list.addFirst(30);
list.addFirst(20);
list.addFirst(10);
System.out.print("adding 30, 20 and 10 at the start: ");
list.traverse();
list.addLast(40);
System.out.print("adding 40 at the end: ");
list.traverse();
System.out.println("contains 30? " + list.contains(30));
list.remove(20);
System.out.print("removing 20: ");
list.traverse();
System.out.println("contains 20? " + list.contains(20));
}
}
Output:
adding 30, 20 and 10 at the start: 10 -> 20 -> 30 -> null adding 40 at the end: 10 -> 20 -> 30 -> 40 -> null contains 30? true removing 20: 10 -> 30 -> 40 -> null contains 20? false
Adding at the start: link first, move later
The addFirst method has two lines, and their order matters. First, the new node points to whoever was first. Only then does head become the new node. Did you notice that 30 went in first and ended up last? Each new value goes in front of all the others.

See the animation of inserting at the start and traversing

At no point did we need to touch the nodes that already existed. Whether the list has 3 or 3 million nodes, inserting at the start takes the same work.
Adding at the end: walking to the last node
The addLast method doesn’t know where the last node is. It starts at head and keeps walking while the next of the current node isn’t null. When it stops, it’s at the last node, and all it has to do is link the new node to it. The longer the list, the longer the walk. You can avoid this walk by also keeping a reference to the last node.
Searching: traversing until you find it
The contains method follows the same path as traverse, but stops as soon as it finds the value. In the worst case, it goes through every node.
To find a value, the only way is to go node by node. That’s why binary search doesn’t go well with a linked list: you can’t jump straight to the middle. Got it?
Removing: redirecting the arrow
The remove method looks for the node that comes before the value, the previous, and makes its arrow skip the removed node: previous.next = previous.next.next. If the value is in the first node, there’s no previous node, and it’s head itself that moves.

And where did node 20 go? Nothing points to it anymore. According to Oracle’s garbage collection guide, an object that can no longer be reached from any reference of another live object is considered garbage, and the virtual machine can reuse its memory. In C, nobody cleans up for you: whoever removes the node has to call free, as you saw in the article on memory allocation.
Now you ask: is a linked list faster than an array?
It depends on the operation, and you can measure it. The program below puts 100,000 values at the start of two lists: an ArrayList, Java’s list that stores the values in an array, and our hand-made list. Then it reads the middle value of each one 10,000 times. Each measurement was repeated 5 times, and the shortest time was kept.
See the measurement program
// Insert at the start and read the middle: the hand-made list against ArrayList
import java.util.ArrayList;
public class Benchmark {
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
}
static final int N = 100_000; // how many values go into each list
static final int READS = 10_000; // how many times the middle value is read
public static void main(String[] args) {
double bestArrayInsert = Double.MAX_VALUE, bestListInsert = Double.MAX_VALUE;
double bestArrayRead = Double.MAX_VALUE, bestListRead = Double.MAX_VALUE;
long arraySum = 0, listSum = 0;
for (int round = 0; round < 5; round++) { // 5 rounds; the fastest one counts
// insert at the start of the ArrayList: each add(0, ...) shifts everything to the right
long t0 = System.nanoTime();
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < N; i++) {
array.add(0, i);
}
bestArrayInsert = Math.min(bestArrayInsert, (System.nanoTime() - t0) / 1e6);
// insert at the start of the hand-made list: one new node and one reference updated
t0 = System.nanoTime();
Node head = null;
for (int i = 0; i < N; i++) {
Node newNode = new Node(i);
newNode.next = head;
head = newNode;
}
bestListInsert = Math.min(bestListInsert, (System.nanoTime() - t0) / 1e6);
// read the middle value in the ArrayList: straight to the position
t0 = System.nanoTime();
arraySum = 0;
for (int k = 0; k < READS; k++) {
arraySum += array.get(N / 2);
}
bestArrayRead = Math.min(bestArrayRead, (System.nanoTime() - t0) / 1e6);
// read the middle value in the hand-made list: walking from the head
t0 = System.nanoTime();
listSum = 0;
for (int k = 0; k < READS; k++) {
Node current = head;
for (int step = 0; step < N / 2; step++) {
current = current.next;
}
listSum += current.value;
}
bestListRead = Math.min(bestListRead, (System.nanoTime() - t0) / 1e6);
}
System.out.printf("inserting 100,000 values at the start: ArrayList %6.1f ms | hand-made list %6.1f ms%n",
bestArrayInsert, bestListInsert);
System.out.printf("reading the middle value 10,000 times: ArrayList %6.1f ms | hand-made list %6.1f ms%n",
bestArrayRead, bestListRead);
System.out.println("is the middle value the same in both? " + (arraySum == listSum));
}
}
Output:
inserting 100,000 values at the start: ArrayList 378.7 ms | hand-made list 0.5 ms reading the middle value 10,000 times: ArrayList 0.0 ms | hand-made list 840.1 ms is the middle value the same in both? true
Each structure won one round and lost the other. At the start, the ArrayList took more than 700 times longer: the Java documentation explains that inserting at a position shifts the element that was there, and every element after it, one place to the right. When reading the middle, the situation is reversed. The get method of ArrayList runs in constant time, also according to the documentation, while our list has to walk 50,000 nodes on every read. It’s the table from above, now with numbers!
What about the other languages?
The concept is the same in all of them: a node with the value and the link to the next one, and a variable that holds the head. In Python and PHP, the node is also a class, the end is None or null, and the language itself takes care of memory. In C, the node is a struct, the next field is a pointer with the address of the next node, and each node is requested with malloc and given back with free. The outputs only change in the way each language writes the end and true or false. Focus on the concept, not the language!
See the same list in Python, PHP and C
Python:
# Hand-made linked list in Python: add, search, remove and traverse
class Node:
def __init__(self, value):
self.value = value
self.next = None # it doesn't point to anyone yet
class SinglyLinkedList:
def __init__(self):
self.head = None # the first node; None while the list is empty
def add_first(self, value):
new_node = Node(value)
new_node.next = self.head # 1st: link the new node to the old first node
self.head = new_node # 2nd: the head becomes the new node
def add_last(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def contains(self, value):
current = self.head
while current is not None:
if current.value == value:
return True
current = current.next
return False
def remove(self, value):
if self.head is None:
return False
if self.head.value == value:
self.head = self.head.next
return True
previous = self.head
while previous.next is not None and previous.next.value != value:
previous = previous.next
if previous.next is None:
return False # reached the end without finding it
previous.next = previous.next.next # skips the removed node
return True
def traverse(self):
current = self.head
while current is not None:
print(current.value, end=" -> ")
current = current.next
print("None")
linked_list = SinglyLinkedList()
linked_list.add_first(30)
linked_list.add_first(20)
linked_list.add_first(10)
print("adding 30, 20 and 10 at the start: ", end="")
linked_list.traverse()
linked_list.add_last(40)
print("adding 40 at the end: ", end="")
linked_list.traverse()
print("contains 30?", linked_list.contains(30))
linked_list.remove(20)
print("removing 20: ", end="")
linked_list.traverse()
print("contains 20?", linked_list.contains(20))
Output:
adding 30, 20 and 10 at the start: 10 -> 20 -> 30 -> None adding 40 at the end: 10 -> 20 -> 30 -> 40 -> None contains 30? True removing 20: 10 -> 30 -> 40 -> None contains 20? False
PHP:
<?php
// Hand-made linked list in PHP: add, search, remove and traverse
class Node
{
public ?Node $next = null; // it doesn't point to anyone yet
public function __construct(public int $value)
{
}
}
class SinglyLinkedList
{
private ?Node $head = null; // the first node; null while the list is empty
public function addFirst(int $value): void
{
$newNode = new Node($value);
$newNode->next = $this->head; // 1st: link the new node to the old first node
$this->head = $newNode; // 2nd: the head becomes the new node
}
public function addLast(int $value): void
{
$newNode = new Node($value);
if ($this->head === null) {
$this->head = $newNode;
return;
}
$current = $this->head;
while ($current->next !== null) {
$current = $current->next;
}
$current->next = $newNode;
}
public function contains(int $value): bool
{
$current = $this->head;
while ($current !== null) {
if ($current->value === $value) {
return true;
}
$current = $current->next;
}
return false;
}
public function remove(int $value): bool
{
if ($this->head === null) {
return false;
}
if ($this->head->value === $value) {
$this->head = $this->head->next;
return true;
}
$previous = $this->head;
while ($previous->next !== null && $previous->next->value !== $value) {
$previous = $previous->next;
}
if ($previous->next === null) {
return false; // reached the end without finding it
}
$previous->next = $previous->next->next; // skips the removed node
return true;
}
public function traverse(): void
{
$current = $this->head;
while ($current !== null) {
echo $current->value, ' -> ';
$current = $current->next;
}
echo 'null', PHP_EOL;
}
}
$list = new SinglyLinkedList();
$list->addFirst(30);
$list->addFirst(20);
$list->addFirst(10);
echo 'adding 30, 20 and 10 at the start: ';
$list->traverse();
$list->addLast(40);
echo 'adding 40 at the end: ';
$list->traverse();
echo 'contains 30? ', var_export($list->contains(30), true), PHP_EOL;
$list->remove(20);
echo 'removing 20: ';
$list->traverse();
echo 'contains 20? ', var_export($list->contains(20), true), PHP_EOL;
Output:
adding 30, 20 and 10 at the start: 10 -> 20 -> 30 -> null adding 40 at the end: 10 -> 20 -> 30 -> 40 -> null contains 30? true removing 20: 10 -> 30 -> 40 -> null contains 20? false
C:
/* Hand-made linked list in C: add, search, remove and traverse */
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next; /* pointer: holds the address of the next node */
};
/* in C, the memory for each node is requested with malloc */
struct Node *new_node(int value) {
struct Node *node = malloc(sizeof(struct Node));
if (node == NULL) {
exit(1); /* out of memory: the program stops */
}
node->value = value;
node->next = NULL;
return node;
}
struct Node *add_first(struct Node *head, int value) {
struct Node *node = new_node(value);
node->next = head; /* 1st: link the new node to the old first node */
return node; /* 2nd: the new node becomes the head */
}
struct Node *add_last(struct Node *head, int value) {
struct Node *node = new_node(value);
if (head == NULL) {
return node;
}
struct Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
return head;
}
int contains(struct Node *head, int value) {
for (struct Node *current = head; current != NULL; current = current->next) {
if (current->value == value) {
return 1;
}
}
return 0;
}
struct Node *remove_value(struct Node *head, int value) {
if (head == NULL) {
return NULL;
}
if (head->value == value) {
struct Node *second = head->next;
free(head); /* in C, whoever removes a node gives its memory back */
return second;
}
struct Node *previous = head;
while (previous->next != NULL && previous->next->value != value) {
previous = previous->next;
}
if (previous->next != NULL) {
struct Node *removed = previous->next;
previous->next = removed->next; /* skips the removed node */
free(removed);
}
return head;
}
void traverse(struct Node *head) {
for (struct Node *current = head; current != NULL; current = current->next) {
printf("%d -> ", current->value);
}
printf("NULL\n");
}
/* gives back the memory of every node that is left */
void free_list(struct Node *head) {
while (head != NULL) {
struct Node *next = head->next;
free(head);
head = next;
}
}
int main(void) {
struct Node *head = NULL;
head = add_first(head, 30);
head = add_first(head, 20);
head = add_first(head, 10);
printf("adding 30, 20 and 10 at the start: ");
traverse(head);
head = add_last(head, 40);
printf("adding 40 at the end: ");
traverse(head);
printf("contains 30? %s\n", contains(head, 30) ? "yes" : "no");
head = remove_value(head, 20);
printf("removing 20: ");
traverse(head);
printf("contains 20? %s\n", contains(head, 20) ? "yes" : "no");
free_list(head);
return 0;
}
Output:
adding 30, 20 and 10 at the start: 10 -> 20 -> 30 -> NULL adding 40 at the end: 10 -> 20 -> 30 -> 40 -> NULL contains 30? yes removing 20: 10 -> 30 -> 40 -> NULL contains 20? no
The C program went through Valgrind with no leaks: every malloc had its free.
Now you ask: do I need to build a linked list by hand?
To learn, yes! In day-to-day work, languages already come with ready-made structures. Java has the LinkedList class, which the documentation describes as a doubly linked list: each node is linked to the next one and also to the previous one, so you can walk in both directions. Its addFirst method does the same job as our addFirst:
// Java's ready-made linked list does the same job as ours
import java.util.LinkedList;
public class BuiltIn {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(30);
list.addFirst(20);
list.addFirst(10);
System.out.println(list); // [10, 20, 30]
}
}
PHP has the SplDoublyLinkedList class, which is also doubly linked. And the linked list is the foundation for other structures on this track: in PHP itself, the SplStack (the stack) and SplQueue (the queue) classes are implemented with a doubly linked list.
What are the most common mistakes with linked lists?
The trickiest one is swapping the two lines of addFirst. I did it on purpose:
// The order mistake: moving the head before linking the new node
public class WrongOrder {
static class Node {
int value;
Node next;
Node(int value) {
this.value = value;
}
}
public static void main(String[] args) {
Node head = new Node(20); // a list with a single node
Node newNode = new Node(10);
head = newNode; // WRONG: moved the head first...
newNode.next = head; // ...and the new node now points to itself
// shows only 6 steps, because this chain never reaches null
Node current = head;
for (int step = 0; step < 6; step++) {
System.out.print(current.value + " -> ");
current = current.next;
}
System.out.println("...");
System.out.println("does the new node point to itself? " + (newNode.next == newNode));
}
}
Output:
10 -> 10 -> 10 -> 10 -> 10 -> 10 -> ... does the new node point to itself? true
The program moved head to the new node and only then made the new node point to head, which is now itself. The chain turned into a circle, and 20 disappeared: nothing points to it anymore. Without the 6-step limit in the for, the traversal would never end. Link first, move later!!!
Other common mistakes:
- Forgetting the empty list. With
headset tonull, awhile (current.next != null)tries to read thenextof nobody, and Java stops withNullPointerException: Cannot read field "next" because "current" is null. The variable name only shows up when the program is compiled withjavac -g; without it, the message shows"<local2>". That’s whyaddLastchecksheadbefore walking. - Walking with
headitself. Iftraversedoeshead = head.next, the list ends up empty after it’s printed. Use a helper variable, likecurrent. - Stopping at the wrong node when removing. To take a node out,
removehas to stop at the node before it. If it stops at the node itself, there’s no way to go back to the arrow that points to it. - Removing without
freein C. Redirecting the arrow takes the node out of the list, but doesn’t give its memory back. Withoutfree, every removal leaks a node.
Now it’s your turn!
Pick one of the four languages and create a method in your list that counts how many nodes it has. A hint: it’s very similar to traverse. Before typing, answer on paper: what changes from one to the other?
Try it on your own first, without asking anyone for the ready-made code. If you get stuck, reread the traverse method calmly, because the answer is almost all there. You’re fully capable of solving it! I’ll show you the answer in the next article.
In the next article, we’ll talk about the queue, the structure of “first come, first served”. See you there!
Stay confident!!!
Sources:
- Stanford University, CS Education Library (Nick Parlante). Linked List Basics, with nodes made of the data and a pointer to the next node, the head pointer and NULL at the end of the list (PDF).
- Stanford University, CS106B. Linked Lists, with the list that keeps a pointer to its front node, NULL as the end of the list and the traversal that loses the list when it moves the front pointer itself (PDF).
- Stanford University, CS106B. More on Linked Lists, with adding to the front by first pointing the new cell to the old head and only then moving the head, and with head and tail pointers.
- Princeton University, Algorithms, 4th Edition (Robert Sedgewick and Kevin Wayne). 1.3 Bags, Queues, and Stacks, with nodes that have an item and a next field, inserting at the beginning as the easiest case and inserting at the end by keeping a link to the last node.
- Virginia Tech, OpenDSA. Pointers Syntax, with the assignment between two references making them share the same object and null as a value that never refers to a legal object.
- Oracle, Java SE 21 documentation. Class LinkedList, with the doubly linked list of the standard library and the
addFirstmethod, which inserts at the beginning. - Oracle, Java SE 21 documentation. Class ArrayList, with the resizable array,
getin constant time andaddat a position, which shifts the following elements to the right. - Oracle. The Java Language Specification, Java SE 21, chapter 4, with references as pointers to objects,
nullas the reference that refers to no object and the initial valuenullof fields of an object type (sections 4.3.1 and 4.12.5). - Oracle. The Java Language Specification, Java SE 21, chapter 15, with
==between references, true when both sides refer to the same object (section 15.21.3). - Oracle. Java 17 Garbage Collection Tuning Guide, Garbage Collector Implementation, with an object considered garbage when no reference of any other live object can reach it anymore.
- Oracle. Java 21 Garbage Collection Tuning Guide, introduction, with the garbage collector that manages memory and frees the programmer from doing it by hand.
- OpenJDK. JEP 330: Launch Single-File Source-Code Programs, with the
javacommand that compiles a single-file program in memory and runs it, since Java 11. - OpenJDK. JEP 358: Helpful NullPointerExceptions, with the message that says which variable was
nulland local variable names that only show up when the local variable table is available, as withjavac -g. - PHP Manual. The SplDoublyLinkedList class, with the doubly linked list of the SPL.
- PHP Manual. The SplStack class, with a stack implemented using a doubly linked list; the SplQueue class does the same for the queue.
- The examples were run on Java 21, Python 3.13, PHP 8.3 and GCC 13. The timing was measured on a virtual machine with a 2.1 GHz Intel Xeon processor; on another machine, the numbers will be different.

Continue the conversation