Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 16 / Topic 8 of 12

Build your own linked list

A linked list is a chain of Nodes, each holding a value and a reference to the next node — no contiguous block of memory the way an array needs. java.util.LinkedList exists (and is doubly linked), but writing a singly linked list by hand once is what makes "insert at the head is O(1)" and "delete needs the previous node, which a singly linked list can't look up backward" stop being trivia you memorized and start being something you've actually hit mid-method. Think of a treasure hunt where each clue only tells you where the next clue is: finding clue #1 is instant, but to remove clue #5 you need to already be holding clue #4 — there's no way to jump back to it from #5 itself.

static final class Node<T> {
    T value;
    Node<T> next;
    Node(T value) { this.value = value; }
}

void addFirst(T value) {           // O(1): no shifting, unlike an array's insert-at-0
    Node<T> node = new Node<>(value);
    node.next = head;
    head = node;
    if (tail == null) tail = node;
    size++;
}
$ javac LinkedListDemo.java
$ java LinkedListDemo
bus stops after addLast x3:  [Pune Station -> Swargate -> Hadapsar] (size 3)
after addFirst("Depot"):     [Depot -> Pune Station -> Swargate -> Hadapsar]
remove("Swargate") -> true:    [Depot -> Pune Station -> Hadapsar]
removeFirst() -> "Depot":  [Pune Station -> Hadapsar]
after reverse():              [Hadapsar -> Pune Station]

-- cycle detection (Floyd's slow/fast pointers) --
no-cycle list has a cycle: false
hand-built cyclic list has a cycle: true

reverse() relinks every next pointer in a single O(n) pass with no extra list — three pointers (previous, current, the saved next) marching together. Cycle detection (Floyd's algorithm, also called the tortoise and hare) uses a slow pointer moving one step and a fast pointer moving two: on a list with a genuine loop, the fast pointer eventually laps the slow one and they land on the same node; on a list with no loop, the fast pointer simply reaches the end first.

Full program: examples/linked-lists/LinkedListDemo.java.

Done here? The practice set for Part 16 — including the solutions — is on the part page.

Search the guide