Skip to lesson

Insert and delete nodes

To insert or delete at index in a singly linked list, stop one step earlier at index - 1. When index == 0, there is no node before head. Placing a dummy head node before head gives every node a predecessor.

Insert at a position and delete by position or value

Inserting or deleting at a position in a singly linked list changes the next link of the node just before that spot (prev). Walk index - 1 steps to prev, then update prev.next.

Java
// For index >= 1 (a dummy head, as in Example 1, also covers index 0)Node prev = head;for (int i = 0; i < index - 1; i++) {    prev = prev.next;                    // stop at the node BEFORE position index}prev.next = new Node(val, prev.next);    // insert: the new node points to the old next// Delete at index instead: prev.next = prev.next.next;

Singly linked nodes only point forward via next. Once curr steps onto the node to delete, you cannot reach back to update the previous node.

  • Insert val at index: set prev.next = new Node(val, prev.next);.
  • Delete at index: set prev.next = prev.next.next;.
  • Delete by value (target): when prev.next.val == target, set prev.next = prev.next.next;.
When deleting all matches of target, do not advance prev right after deleting prev.next. The new prev.next might also equal target.

The dummy head node (sentinel node)

A dummy head node is a temporary node placed before head (Node dummy = new Node(0, head)) so that head has a predecessor and needs no special case.

Without a helper node, changing head needs a separate if (index == 0) check because head has no predecessor. We give head a predecessor by creating Node dummy = new Node(0, head);.

  1. Create Node dummy = new Node(0, head);.
  2. Start your cursor at Node prev = dummy;.
  3. Insert or delete through prev.next with no special case for head.
  4. Return dummy.next as the new head of the list.

Example 1 · Insert and Delete at Any Position Using a Dummy Head Node

InsertDeleteAtIndexDemo.javaJava
public class InsertDeleteAtIndexDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node insertAt(Node head, int index, int val) {        Node dummy = new Node(0, head);        Node prev = dummy;        for (int i = 0; i < index && prev != null; i++) {            prev = prev.next;        }        if (prev == null) throw new IndexOutOfBoundsException("Index: " + index);        prev.next = new Node(val, prev.next);        return dummy.next;    }
    public static Node deleteAt(Node head, int index) {        Node dummy = new Node(0, head);        Node prev = dummy;        for (int i = 0; i < index && prev.next != null; i++) {            prev = prev.next;        }        if (prev.next == null) throw new IndexOutOfBoundsException("Index: " + index);        prev.next = prev.next.next;        return dummy.next;    }
    static String format(Node head) {        StringBuilder sb = new StringBuilder();        for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node head = null;        head = insertAt(head, 0, 20);        head = insertAt(head, 0, 10);        head = insertAt(head, 2, 40);        head = insertAt(head, 2, 30);        System.out.println("After inserts: " + format(head));
        head = deleteAt(head, 0);        head = deleteAt(head, 1);        System.out.println("After deletes: " + format(head));    }}
Output
After inserts: 10 -> 20 -> 30 -> 40 -> null
After deletes: 20 -> 40 -> null

What this code does

  • When index == 0, the loop runs 0 times, prev stays at dummy, and prev.next updates dummy.next.
  • Returning dummy.next always gives the current head, even when the list becomes empty.

Example 2 · Remove All Occurrences of a Value with a Dummy Head

RemoveElementsByValueDemo.javaJava
public class RemoveElementsByValueDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static Node removeAll(Node head, int target) {        Node dummy = new Node(0, head);        Node prev = dummy;        while (prev.next != null) {            if (prev.next.val == target) {                prev.next = prev.next.next; // Bypass target; keep prev where it is!            } else {                prev = prev.next;           // Only advance prev when prev.next is kept            }        }        return dummy.next;    }
    static String format(Node head) {        StringBuilder sb = new StringBuilder();        for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" -> ");        return sb.append("null").toString();    }
    public static void main(String[] args) {        Node a = new Node(6, new Node(6, new Node(1, new Node(6, new Node(2, new Node(6, null))))));        System.out.println("Removed 6s from [6,6,1,6,2,6]: " + format(removeAll(a, 6)));
        Node allSix = new Node(6, new Node(6, new Node(6, null)));        System.out.println("Removed 6s from [6,6,6]:       " + format(removeAll(allSix, 6)));    }}
Output
Removed 6s from [6,6,1,6,2,6]: 1 -> 2 -> null
Removed 6s from [6,6,6]:       null

What this code does

  • When prev.next.val == 6, we unlink prev.next and keep prev still so the next 6 is checked too.
  • When every node in [6, 6, 6] is removed, dummy.next becomes null and is returned.

Example 3 · Design Linked List Using a Dummy Sentinel Head

DesignLinkedListDemo.javaJava
public class DesignLinkedListDemo {    static class MyLinkedList {        private static class Node {            int val;            Node next;            Node(int val, Node next) { this.val = val; this.next = next; }        }
        private final Node dummy = new Node(0, null);        private int size = 0;
        public int get(int index) {            if (index < 0 || index >= size) return -1;            Node curr = dummy.next;            for (int i = 0; i < index; i++) curr = curr.next;            return curr.val;        }
        public void addAtIndex(int index, int val) {            if (index < 0 || index > size) return;            Node prev = dummy;            for (int i = 0; i < index; i++) prev = prev.next;            prev.next = new Node(val, prev.next);            size++;        }
        public void addAtHead(int val) { addAtIndex(0, val); }        public void addAtTail(int val) { addAtIndex(size, val); }
        public void deleteAtIndex(int index) {            if (index < 0 || index >= size) return;            Node prev = dummy;            for (int i = 0; i < index; i++) prev = prev.next;            prev.next = prev.next.next;            size--;        }    }
    public static void main(String[] args) {        MyLinkedList list = new MyLinkedList();        list.addAtHead(1);        list.addAtTail(3);        list.addAtIndex(1, 2); // 1 -> 2 -> 3        System.out.println("get(1) = " + list.get(1));        list.deleteAtIndex(1); // 1 -> 3        System.out.println("get(1) after delete = " + list.get(1));    }}
Output
get(1) = 2
get(1) after delete = 3

What this code does

  • Storing a permanent dummy node inside MyLinkedList means the real head is always dummy.next.
  • addAtHead(val) and addAtTail(val) simply call addAtIndex(0, val) and addAtIndex(size, val).

With dummy placed before index 0, every real node has a node before it. Start prev = dummy, run one loop, and return dummy.next; as the updated head.

Null pointer traps

A NullPointerException (NPE) is thrown when code reads a field such as curr.val or curr.next through a null reference. Most crashes in linked list code are NPEs; watch out for these four traps.

Java
boolean safe = curr != null && curr.val == x;   // && stops at the null check: falseboolean crash = curr.val == x && curr != null;  // reads curr.val first: NullPointerException
  • Trap 1 — Reading curr.next.val when curr.next == null: Always check curr != null && curr.next != null first.
  • Trap 2 — Moving prev after deleting prev.next: Only advance prev = prev.next in else when prev.next is kept.
  • Trap 3 — Wrong order in &&: Write curr != null && curr.val == x, never curr.val == x && curr != null.
  • Trap 4 — Empty list (head == null): Starting with Node dummy = new Node(0, head) handles head == null cleanly because dummy is never null.

Fix the error

Fix the null pointer crash

Read the error, then pick the line that fixes it.

Round 1 of 2

Search for x in a list that does not contain it.

Node curr = head;
while (curr.val != x && curr != null) {
curr = curr.next;
}

Error

Exception in thread "main" java.lang.NullPointerException: Cannot read field "val" because "curr" is null

Next step

Check your understanding

10 quick questions