AlgoTales · Roadmap

Insertion/deletion

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

Where you will meet this in real life

Insertion and deletion in a linked list mean changing a couple of links instead of shifting everything. To put an item in, you point the new item at its follower and its predecessor at it. To remove one, you make its neighbours link to each other.

Practical use cases

  • Web app: Cancel one job in a print or export queue. A reporting page queues exports for users, and a user clicks Cancel on the third one. In a chain, you relink the second export to the fourth and the third vanishes. Nothing else is moved, so cancelling is instant even with thousands waiting.
  • Web app: Drag-and-drop reordering of a to-do list. In a task board, dragging a card between two others should not renumber the entire list. Treating the cards as a chain, the dropped card is linked between its new neighbours and unlinked from the old place. Two or three link changes finish the job.
  • System: Memory allocators and playlists. Memory managers keep a chain of free blocks and splice blocks in and out as programs request and release memory. Media players do the same when you add or remove a song from the middle of a queue, so the rest of the playlist never has to be rewritten or renumbered.

The story: Cutting the Chai Queue

Raju's chai stall was famous, and so was the queue. People did not stand in a straight row on the road. Each customer simply remembered the person standing behind them. Raju only needed to know the first customer; the rest of the queue followed like a chain.

One evening Mrs. Sharma arrived late with a sick neighbour and asked politely: "May I stand right after Mr. Joshi?" Raju did not ask 12 people to shuffle. He did two small things: first he told Mrs. Sharma "you stand before the man behind Mr. Joshi", then he told Mr. Joshi "you now stand before Mrs. Sharma".

Raju learnt the hard way that the order matters. Once, he told Mr. Joshi to point at the newcomer first, and the whole rest of the queue, who had been remembered only through Mr. Joshi, vanished from his sight! After that: first connect the newcomer forward, then connect the previous person to the newcomer.

Deleting is even simpler. When a customer leaves, the person in front of them just changes who they point at: prev.next = prev.next.next. That is insertion and deletion in a linked list: no shifting, just rewiring one or two pointers once you are standing at the right place. Finding the right place is the part that costs a walk.

How to spot this problem, and where you need it

You keep inserting or removing items in the middle of a list, and every change makes the program shuffle all the later items, which is slow for big lists.

Signs you need it

  • Your code calls array_splice or splice in a loop on a large list and the CPU time climbs with each operation.
  • You already hold a reference to the item (or the one before it), so you do not have to search for it.
  • The task describes "insert after node X" or "delete this node" for many operations in a row.

Where to use it in a project

  • Reordering features such as drag-and-drop lists, playlists and kanban cards.
  • Cancelling or prioritising items in a waiting queue of jobs or orders.
  • Custom allocators, pools and caches that constantly add and drop entries.

The solution

To insert, create the new box, set its next link to the box that should follow it, then set the previous box's link to the new box. To delete, set the previous box's link to the box after the one being removed. Always do the new links in the right order so you never lose the rest of the chain. Only two or three links change.

Payoff: Before: moving up to 100,000 items for each change. After: two or three link updates, however long the list.

Explain it like I am 8

In a queue where everyone holds the shoulder of the person behind, a new kid can jump in: she holds the shoulder of the kid who was behind, then the kid in front lets go of that one and holds her. Nobody else moves.

How it works, step by step

  1. Walk to the spot: stand on the node before where you want to insert or delete (the predecessor).
  2. Insert after prev: new.next = prev.next first, then prev.next = new.
  3. Delete after prev: prev.next = prev.next.next. The skipped node is now unreachable.
  4. At the front: there is no predecessor. Insert: new.next = head; head = new. Delete: head = head.next.
  5. A dummy node in front of the head removes the special cases: every real node then has a predecessor.

The code in four languages

PHP

<?php
class Node {
    public $val;
    public ?Node $next = null;
    public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}

function fromArray(array $vals): ?Node {
    $head = null;
    foreach (array_reverse($vals) as $v) { $head = new Node($v, $head); }
    return $head;
}
function show(?Node $head): string {
    $out = [];
    for ($c = $head; $c !== null; $c = $c->next) $out[] = $c->val;
    return implode(' -> ', $out) . ' -> null';
}

// insert $val right after the node $prev
function insertAfter(Node $prev, $val): void {
    $new = new Node($val);
    $new->next = $prev->next;   // 1) new points forward first
    $prev->next = $new;         // 2) then the previous node points to new
}

// delete the first node holding $val; returns the (maybe new) head
function deleteValue(?Node $head, $val): ?Node {
    $dummy = new Node(0, $head);          // dummy: even the head has a predecessor
    $prev = $dummy;
    while ($prev->next !== null && $prev->next->val !== $val) { $prev = $prev->next; }
    if ($prev->next !== null) { $prev->next = $prev->next->next; }   // skip it
    return $dummy->next;
}

$head = fromArray(['A', 'B', 'C', 'D']);
echo show($head) . "\n";
insertAfter($head->next, 'X');            // after B
echo show($head) . "\n";                 // A -> B -> X -> C -> D
$head = deleteValue($head, 'C');
echo show($head) . "\n";                 // A -> B -> X -> D
$head = deleteValue($head, 'A');          // deleting the head works too
echo show($head) . "\n";                 // B -> X -> D

JavaScript

class Node {
  constructor(val, next = null) { this.val = val; this.next = next; }
}

function fromArray(vals) {
  let head = null;
  for (let i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
  return head;
}
function show(head) {
  const out = [];
  for (let c = head; c !== null; c = c.next) out.push(c.val);
  return out.join(' -> ') + ' -> null';
}

// insert val right after the node prev
function insertAfter(prev, val) {
  const node = new Node(val);
  node.next = prev.next;      // 1) new points forward first
  prev.next = node;           // 2) then the previous node points to new
}

// delete the first node holding val; returns the (maybe new) head
function deleteValue(head, val) {
  const dummy = new Node(0, head);        // dummy: even the head has a predecessor
  let prev = dummy;
  while (prev.next !== null && prev.next.val !== val) prev = prev.next;
  if (prev.next !== null) prev.next = prev.next.next;   // skip it
  return dummy.next;
}

let head = fromArray(['A', 'B', 'C', 'D']);
console.log(show(head));
insertAfter(head.next, 'X');              // after B
console.log(show(head));                  // A -> B -> X -> C -> D
head = deleteValue(head, 'C');
console.log(show(head));                  // A -> B -> X -> D
head = deleteValue(head, 'A');            // deleting the head works too
console.log(show(head));                  // B -> X -> D

Java

import java.util.*;

public class Main {
    static class Node {
        String val;
        Node next;
        Node(String val, Node next) { this.val = val; this.next = next; }
    }

    static Node fromArray(String[] vals) {
        Node head = null;
        for (int i = vals.length - 1; i >= 0; i--) { head = new Node(vals[i], head); }
        return head;
    }

    static String show(Node head) {
        List<String> out = new ArrayList<>();
        for (Node c = head; c != null; c = c.next) out.add(c.val);
        return String.join(" -> ", out) + " -> null";
    }

    // insert val right after the node prev
    static void insertAfter(Node prev, String val) {
        Node node = new Node(val, null);
        node.next = prev.next;     // 1) new points forward first
        prev.next = node;          // 2) then the previous node points to new
    }

    // delete the first node holding val; returns the (maybe new) head
    static Node deleteValue(Node head, String val) {
        Node dummy = new Node("", head);       // dummy: even the head has a predecessor
        Node prev = dummy;
        while (prev.next != null && !prev.next.val.equals(val)) { prev = prev.next; }
        if (prev.next != null) { prev.next = prev.next.next; }   // skip it
        return dummy.next;
    }

    public static void main(String[] args) {
        Node head = fromArray(new String[]{"A", "B", "C", "D"});
        System.out.println(show(head));
        insertAfter(head.next, "X");               // after B
        System.out.println(show(head));            // A -> B -> X -> C -> D -> null
        head = deleteValue(head, "C");
        System.out.println(show(head));            // A -> B -> X -> D -> null
        head = deleteValue(head, "A");             // deleting the head works too
        System.out.println(show(head));            // B -> X -> D -> null
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type Node struct {
	val  string
	next *Node
}

func fromSlice(vals []string) *Node {
	var head *Node
	for i := len(vals) - 1; i >= 0; i-- {
		head = &Node{val: vals[i], next: head}
	}
	return head
}

func show(head *Node) string {
	var out []string
	for c := head; c != nil; c = c.next {
		out = append(out, c.val)
	}
	return strings.Join(out, " -> ") + " -> nil"
}

// insertAfter puts val right after the node prev.
func insertAfter(prev *Node, val string) {
	node := &Node{val: val}
	node.next = prev.next // 1) new points forward first
	prev.next = node      // 2) then the previous node points to new
}

// deleteValue removes the first node holding val; returns the (maybe new) head.
func deleteValue(head *Node, val string) *Node {
	dummy := &Node{next: head} // dummy: even the head has a predecessor
	prev := dummy
	for prev.next != nil && prev.next.val != val {
		prev = prev.next
	}
	if prev.next != nil {
		prev.next = prev.next.next // skip it
	}
	return dummy.next
}

func main() {
	head := fromSlice([]string{"A", "B", "C", "D"})
	fmt.Println(show(head))
	insertAfter(head.next, "X") // after B
	fmt.Println(show(head))     // A -> B -> X -> C -> D -> nil
	head = deleteValue(head, "C")
	fmt.Println(show(head))       // A -> B -> X -> D -> nil
	head = deleteValue(head, "A") // deleting the head works too
	fmt.Println(show(head))       // B -> X -> D -> nil
}

Time: O(1) once at the spot, O(n) to find the spot · Extra space: O(1). The rewiring itself is a couple of pointer changes; the walk to the right place is what costs.

Watch out for

  • Wrong order on insert: prev.next = new before new.next = prev.next loses the rest of the list (or makes the new node point to itself).
  • Trying to delete the node you are standing on: you need its predecessor in a singly linked list.
  • Not handling the head: deleting the first node changes head. A dummy node avoids this bug.

Quick check

  1. To insert X after B, which order is safe?
    • B.next = X, then X.next = B.next
    • X.next = B.next, then B.next = X
    • Either order works
    • Only X.next = X
  2. Which pointer change removes the node after prev?
    • prev = prev.next
    • prev.next = prev
    • prev.next = prev.next.next
    • head = prev.next
  3. Why is a dummy node before the head useful?
    • It stores the length
    • It makes the list faster
    • It sorts the list
    • It gives even the first node a predecessor, so no special case