Skip to lesson

Build a singly linked list

Tracking head, tail, and size gives O(1) front insertion, O(1) back insertion, and O(1) size checks.

Add first and add last with head and tail

A node is one element of a linked structure: it stores a value and references (links) to other nodes, such as next in a linked list.

addFirst inserts a node before head, and addLast appends a node after the last one. Storing both Node head and Node tail makes insertions at both ends O(1); with only Node head, addLast(int val) walks the whole list in O(n) time.

Java
void addFirst(int val) {    head = new Node(val, head);    if (tail == null) tail = head;           // list was empty: the new node is also the tail    size++;}
void addLast(int val) {    Node n = new Node(val, null);    if (tail == null) { head = tail = n; }   // empty list: one node is both head and tail    else { tail.next = n; tail = n; }        // link after the old tail, no walking: O(1)    size++;}

Whenever you change a list with head and tail, check the empty-list case (head == null). When a list has one node, head and tail must point to that same node.

  1. addFirst(int val): Set head = new Node(val, head);. If tail == null, set tail = head;. Increment size++.
  2. addLast(int val): Create Node n = new Node(val, null);. If tail == null, set head = tail = n;, else set tail.next = n; tail = n;. Increment size++.
Forgetting if (tail == null) tail = head; in addFirst leaves tail as null and breaks the next addLast call.

Traverse, print, and search

To traverse a list without losing the front, never move head itself. Start a local variable Node curr = head; and advance curr = curr.next until curr == null.

Example 1 · Searching a Linked List: indexOf, contains, and get

SearchLinkedListDemo.javaJava
public class SearchLinkedListDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    public static int indexOf(Node head, int target) {        int idx = 0;        for (Node curr = head; curr != null; curr = curr.next) {            if (curr.val == target) {                return idx;            }            idx++;        }        return -1;    }
    public static boolean contains(Node head, int target) {        return indexOf(head, target) != -1;    }
    public static void main(String[] args) {        Node head = new Node(12, new Node(24, new Node(36, new Node(24, null))));        System.out.println("indexOf(24) = " + indexOf(head, 24));        System.out.println("indexOf(36) = " + indexOf(head, 36));        System.out.println("indexOf(99) = " + indexOf(head, 99));        System.out.println("contains(12) = " + contains(head, 12));    }}
Output
indexOf(24) = 1
indexOf(36) = 2
indexOf(99) = -1
contains(12) = true

What this code does

  • indexOf returns on the first node with curr.val == target (index 1 for 24).
  • When head is null or target is absent, the loop ends and returns -1.

Example 2 · Why while (curr != null) vs while (curr.next != null) Matters

LoopConditionTrapDemo.javaJava
public class LoopConditionTrapDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    static int countBuggy(Node head) {        if (head == null) return 0;        int count = 0;        Node curr = head;        while (curr.next != null) { // Stops BEFORE counting the last node!            count++;            curr = curr.next;        }        return count;    }
    static int countCorrect(Node head) {        int count = 0;        for (Node curr = head; curr != null; curr = curr.next) {            count++;        }        return count;    }
    public static void main(String[] args) {        Node head = new Node(10, new Node(20, new Node(30, null)));        System.out.println("countBuggy:   " + countBuggy(head));        System.out.println("countCorrect: " + countCorrect(head));    }}
Output
countBuggy:   2
countCorrect: 3

What this code does

  • while (curr.next != null) stops as soon as curr reaches the tail node (30), so it misses the last node.
  • for (Node curr = head; curr != null; curr = curr.next) visits all 3 nodes and handles head == null cleanly.

What the loops do:

  • while (curr != null) visits all n nodes and ends with curr == null.
  • indexOf(target) returns the first matching 0-based index, or -1 if missing.
  • contains(target) returns indexOf(target) != -1.

Choose the loop condition based on where curr should stop:

  • Use while (curr != null) to visit every node (printing, summing, counting, or searching).
  • Use while (curr.next != null) (when curr != null) to stop on the last node. To search for target, walk curr from head while counting index from 0. Return index when curr.val == target, or -1 when curr reaches null.

Find the bug

Find the bug in each method

Select the line that is wrong.

This should count every node of the list.

Round 1 of 3

Tracking the size

Without a size field, finding the length walks all n nodes from head in O(n) time.

Keep a private int size field: add 1 on insert and subtract 1 on remove. Now size() and isEmpty() run in O(1) time.

Example 3 · Complete SinglyLinkedList Class with addFirst, addLast, size, and toString

SinglyLinkedListDemo.javaJava
public class SinglyLinkedListDemo {    static class SinglyLinkedList {        private static class Node {            int val;            Node next;            Node(int val, Node next) {                this.val = val;                this.next = next;            }        }
        private Node head;        private Node tail;        private int size;
        public void addFirst(int val) {            head = new Node(val, head);            if (tail == null) {                tail = head;            }            size++;        }
        public void addLast(int val) {            Node n = new Node(val, null);            if (tail == null) {                head = tail = n;            } else {                tail.next = n;                tail = n;            }            size++;        }
        public int size() {            return size;        }
        @Override        public String toString() {            StringBuilder sb = new StringBuilder("[");            for (Node curr = head; curr != null; curr = curr.next) {                sb.append(curr.val);                if (curr.next != null) sb.append(" -> ");            }            return sb.append("]").toString();        }    }
    public static void main(String[] args) {        SinglyLinkedList list = new SinglyLinkedList();        System.out.println("Empty: " + list + " (size=" + list.size() + ")");        list.addLast(20);        list.addFirst(10);        list.addLast(30);        list.addFirst(5);        System.out.println("After adds: " + list + " (size=" + list.size() + ")");    }}
Output
Empty: [] (size=0)
After adds: [5 -> 10 -> 20 -> 30] (size=4)

What this code does

  • list.addLast(20) on an empty list sets both head and tail to Node(20).
  • Every addFirst and addLast runs in O(1) time without walking the list.

Three states every list method must keep correct:

  • Empty list rule: size == 0, head == null, and tail == null.
  • One-node rule: size == 1, head == tail, and head.next == null.
  • Multi-node rule: size >= 2, head != tail, and tail.next == null.

Next step

Check your understanding

10 quick questions