AlgoTales · Roadmap

Singly linked list

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A singly linked list is a chain of items where each item holds its value and a pointer to the next item. You keep hold of the first one and follow the chain. Adding or removing at the front is instant because nothing else has to shift.

Practical use cases

  • Web app: Undo history in a drawing or form editor. A web-based drawing tool saves each action as a step. Pressing Undo takes off the latest step, and every new action is put on the front. Because adding and removing at the front of a chain needs no shifting, a long editing session stays smooth even after thousands of actions.
  • Web app: Newest-first activity feed in memory. A dashboard shows the latest 20 events, newest on top. New events are added at the head of the chain in one step, and the page simply walks the first 20 links to render. Nothing is copied or moved when a new event arrives.
  • System: Memory managers and building blocks. Operating systems often track free pieces of memory as a chain, handing out the first one and putting freed ones back at the front. Stacks, queues and the buckets inside hash tables are also commonly built from this same simple chain, because it grows and shrinks one item at a time without any waste.

The story: The Treasure Hunt Clues

For Zoya's birthday, her dad hid a gift and made a treasure hunt. There was no map. Instead, each paper slip said two things: "what is here" and "where to find the next slip". The first slip was in Zoya's hand. The second was under the sofa cushion. The third was inside a shoe.

Zoya's cousin Aarav complained: "If I want the 5th slip, I cannot teleport. I must follow slip 1, slip 2, slip 3, slip 4." Right, and that is the price. But there was a big upside. When dad wanted to add one more clue in the middle, he just wrote the new slip and changed one line on the slip before it. Nobody had to shift the furniture.

Compare that with Zoya's row of boxes on a shelf (an array). Adding a box in the middle meant pushing every box after it. The treasure hunt does not need all slips next to each other, because every slip knows its successor.

That is a singly linked list: little boxes called nodes, each holding a value and one arrow (next) to the following node. You only keep the first node, the head. The last node's arrow points to null, the "no more clues" signal.

How to spot this problem, and where you need it

You keep adding and removing items at the front or in the middle of a list, and an array keeps moving every other item over to make room, which becomes slow for large lists.

Signs you need it

  • Your code inserts at the beginning of an array (array_unshift, splice) in a loop and the page slows down as the list grows.
  • The size is unknown or changes constantly, and you rarely need to jump straight to the 500th item by position.
  • You are building a stack, undo chain or queue and need very fast add and remove at one end.

Where to use it in a project

  • Undo and redo chains in editors, form builders and drawing tools.
  • Building queues, stacks or bucket lists inside custom data structures.
  • Streaming pipelines that add items at the head and process them in order.

The solution

Store each item as a small box with two parts: the value and a link to the next box. Keep a single reference to the first box. To add at the front, make a new box that links to the old first box and make it the first. To remove the front, move the reference to the next box. No other items are touched.

Payoff: Before: shifting 100,000 items for every insert at the front. After: one step per insert, no matter how long the list is.

Explain it like I am 8

It is a treasure hunt. Every clue tells you something and also tells you where the next clue is hiding. You hold only the first clue, and you follow the trail one clue at a time until a clue says "the end".

How it works, step by step

  1. A node has two parts: a val (the data) and a next (a pointer to another node, or null).
  2. Keep one variable, head, pointing at the first node. An empty list has head = null.
  3. Append: walk from head until next is null, then hang the new node there.
  4. Prepend: make the new node point at the old head, then move head to the new node. That is instant.
  5. Traverse: cur = head, then keep doing cur = cur.next until cur becomes null.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;      // arrow to the next node (null = end)
    public function __construct($val) { $this->val = $val; }
}

class SinglyLinkedList {
    public ?Node $head = null;      // we only remember the first node

    public function prepend($val): void {   // O(1)
        $node = new Node($val);
        $node->next = $this->head;  // new node points at the old head
        $this->head = $node;        // head now points at the new node
    }

    public function append($val): void {    // O(n): must walk to the end
        $node = new Node($val);
        if ($this->head === null) { $this->head = $node; return; }
        $cur = $this->head;
        while ($cur->next !== null) { $cur = $cur->next; }
        $cur->next = $node;
    }

    public function find($val): int {       // index of val, or -1
        $i = 0;
        for ($cur = $this->head; $cur !== null; $cur = $cur->next, $i++) {
            if ($cur->val === $val) return $i;
        }
        return -1;
    }

    public function toArray(): array {
        $out = [];
        for ($cur = $this->head; $cur !== null; $cur = $cur->next) { $out[] = $cur->val; }
        return $out;
    }
}

$list = new SinglyLinkedList();
$list->append(20);
$list->append(30);
$list->append(40);
$list->prepend(10);
echo implode(' -> ', $list->toArray()) . " -> null\n";   // 10 -> 20 -> 30 -> 40 -> null
echo "30 is at index " . $list->find(30) . "\n";            // 2

JavaScript

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;               // arrow to the next node (null = end)
  }
}

class SinglyLinkedList {
  constructor() { this.head = null; }   // we only remember the first node

  prepend(val) {                        // O(1)
    const node = new Node(val);
    node.next = this.head;              // new node points at the old head
    this.head = node;                   // head now points at the new node
  }

  append(val) {                         // O(n): must walk to the end
    const node = new Node(val);
    if (this.head === null) { this.head = node; return; }
    let cur = this.head;
    while (cur.next !== null) cur = cur.next;
    cur.next = node;
  }

  find(val) {                           // index of val, or -1
    let i = 0;
    for (let cur = this.head; cur !== null; cur = cur.next, i++) {
      if (cur.val === val) return i;
    }
    return -1;
  }

  toArray() {
    const out = [];
    for (let cur = this.head; cur !== null; cur = cur.next) out.push(cur.val);
    return out;
  }
}

const list = new SinglyLinkedList();
list.append(20);
list.append(30);
list.append(40);
list.prepend(10);
console.log(list.toArray().join(' -> ') + ' -> null');   // 10 -> 20 -> 30 -> 40 -> null
console.log('30 is at index ' + list.find(30));            // 2

Java

import java.util.*;

public class Main {
    static class Node {
        int val;
        Node next = null;               // arrow to the next node (null = end)
        Node(int val) { this.val = val; }
    }

    static class SinglyLinkedList {
        Node head = null;               // we only remember the first node

        void prepend(int val) {         // O(1)
            Node node = new Node(val);
            node.next = head;           // new node points at the old head
            head = node;                // head now points at the new node
        }

        void append(int val) {          // O(n): must walk to the end
            Node node = new Node(val);
            if (head == null) { head = node; return; }
            Node cur = head;
            while (cur.next != null) { cur = cur.next; }
            cur.next = node;
        }

        int find(int val) {             // index of val, or -1
            int i = 0;
            for (Node cur = head; cur != null; cur = cur.next, i++) {
                if (cur.val == val) return i;
            }
            return -1;
        }

        List<Integer> toList() {
            List<Integer> out = new ArrayList<>();
            for (Node cur = head; cur != null; cur = cur.next) { out.add(cur.val); }
            return out;
        }
    }

    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList();
        list.append(20);
        list.append(30);
        list.append(40);
        list.prepend(10);
        StringBuilder sb = new StringBuilder();
        for (int v : list.toList()) sb.append(v).append(" -> ");
        System.out.println(sb + "null");                     // 10 -> 20 -> 30 -> 40 -> null
        System.out.println("30 is at index " + list.find(30));   // 2
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type Node struct {
	val  int
	next *Node // arrow to the next node (nil = end)
}

type SinglyLinkedList struct {
	head *Node // we only remember the first node
}

func (l *SinglyLinkedList) Prepend(val int) { // O(1)
	node := &Node{val: val}
	node.next = l.head // new node points at the old head
	l.head = node      // head now points at the new node
}

func (l *SinglyLinkedList) Append(val int) { // O(n): must walk to the end
	node := &Node{val: val}
	if l.head == nil {
		l.head = node
		return
	}
	cur := l.head
	for cur.next != nil {
		cur = cur.next
	}
	cur.next = node
}

// Find returns the index of val, or -1.
func (l *SinglyLinkedList) Find(val int) int {
	i := 0
	for cur := l.head; cur != nil; cur = cur.next {
		if cur.val == val {
			return i
		}
		i++
	}
	return -1
}

func (l *SinglyLinkedList) ToSlice() []int {
	var out []int
	for cur := l.head; cur != nil; cur = cur.next {
		out = append(out, cur.val)
	}
	return out
}

func main() {
	list := &SinglyLinkedList{}
	list.Append(20)
	list.Append(30)
	list.Append(40)
	list.Prepend(10)
	var parts []string
	for _, v := range list.ToSlice() {
		parts = append(parts, strconv.Itoa(v))
	}
	fmt.Println(strings.Join(parts, " -> ") + " -> nil") // 10 -> 20 -> 30 -> 40 -> nil
	fmt.Println("30 is at index", list.Find(30))         // 2
}

Time: O(1) prepend, O(n) append/search/access · Extra space: O(n). You can only reach a node by walking from the head, so anything that needs "the k-th item" costs a walk.

Watch out for

  • Losing the head: if you move head forward while walking, the front of the list is gone. Walk with a separate cur variable.
  • Forgetting the empty-list case: head is null, so head.next crashes.
  • Assuming you can jump to index k like an array. A linked list has no random access.

Quick check

  1. What does the last node of a singly linked list point to?
    • The head
    • null
    • The previous node
    • Itself
  2. Which operation is instant (constant time) on a singly linked list?
    • Finding the last node
    • Reading the 100th item
    • Adding a new node at the front
    • Searching for a value
  3. While walking the list you do head = head.next. What goes wrong?
    • Nothing, it is the normal way
    • You lose the start of the list
    • The list becomes sorted
    • It becomes circular