Insert and delete nodes
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
// 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
valatindex: setprev.next = new Node(val, prev.next);. - Delete at
index: setprev.next = prev.next.next;. - Delete by value (
target): whenprev.next.val == target, setprev.next = prev.next.next;.
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);.
- Create
Node dummy = new Node(0, head);. - Start your cursor at
Node prev = dummy;. - Insert or delete through
prev.nextwith no special case forhead. - Return
dummy.nextas the new head of the list.
Example 1 · Insert and Delete at Any Position Using a Dummy Head Node
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)); }}After inserts: 10 -> 20 -> 30 -> 40 -> null After deletes: 20 -> 40 -> null
What this code does
- When
index == 0, the loop runs 0 times,prevstays atdummy, andprev.nextupdatesdummy.next. - Returning
dummy.nextalways gives the currenthead, even when the list becomes empty.
Example 2 · Remove All Occurrences of a Value with a Dummy Head
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))); }}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 unlinkprev.nextand keepprevstill so the next6is checked too. - When every node in
[6, 6, 6]is removed,dummy.nextbecomesnulland is returned.
Example 3 · Design Linked List Using a Dummy Sentinel Head
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)); }}get(1) = 2 get(1) after delete = 3
What this code does
- Storing a permanent
dummynode insideMyLinkedListmeans the real head is alwaysdummy.next. addAtHead(val)andaddAtTail(val)simply calladdAtIndex(0, val)andaddAtIndex(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.
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.valwhencurr.next == null: Always checkcurr != null && curr.next != nullfirst. - Trap 2 — Moving
prevafter deletingprev.next: Only advanceprev = prev.nextinelsewhenprev.nextis kept. - Trap 3 — Wrong order in
&&: Writecurr != null && curr.val == x, nevercurr.val == x && curr != null. - Trap 4 — Empty list (
head == null): Starting withNode dummy = new Node(0, head)handleshead == nullcleanly becausedummyis nevernull.
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.
Error
Exception in thread "main" java.lang.NullPointerException: Cannot read field "val" because "curr" is null
Next step
Check your understanding
10 quick questions