Skip to lesson

Why linked lists exist

An array stores all elements side by side in one memory block. Index lookup arr[i] is O(1), but front insertion shifts up to n items. A linked list stores each value in a node object pointing to the next node.

Arrays versus nodes in memory

A linked list is a chain of nodes where each node holds a value and a reference to the next node. Adding or removing at a known node is O(1), but reaching the i-th node is O(n).

A singly linked list stores items in separate objects called nodes, while an array keeps them in one block of memory. Each node holds val (the value) and next (a reference to the next node). The last node has next == null.

Java
class Node {    int val;       // the value    Node next;     // the next node, or null at the end    Node(int val, Node next) { this.val = val; this.next = next; }}int[] arr = {10, 20, 30};                                     // one block of 3 slotsNode head = new Node(10, new Node(20, new Node(30, null)));  // 3 separate node objects

When you run new int[5], Java reserves one block of 5 slots in memory. From the start address, the CPU finds arr[i] in one step (O(1) time). When an ArrayList fills up, it must allocate a bigger array and copy all n items. Inserting at index 0 also shifts every item one slot right in O(n) time.

The list only needs a reference to the first node, called head. When the list is empty, head is null. Inserting or removing a node at a known spot only rewires one or two next links.

  • Contiguous array: instant arr[i] lookup in O(1), but front or middle shifts take O(n).
  • Linked nodes: no shifting on insert, but reaching index i walks i steps from head.
  • Memory use: each Node object has header and pointer fields, so it uses more memory than int[].

A Node class with next

For pointer problems, we write a small static class Node with int val and Node next fields. A one-arg constructor Node(int val) leaves next = null, while Node(int val, Node next) wires both fields at once.

  1. Create three nodes: Node a = new Node(10); Node b = new Node(20); Node c = new Node(30);.
  2. Link a to b: a.next = b; (10 -> 20 -> null).
  3. Link b to c: b.next = c; (10 -> 20 -> 30 -> null).
  4. Or chain the two-argument constructor: Node head = new Node(10, new Node(20, new Node(30, null)));.

Example 1 · Creating and Wiring Nodes by Hand

ManualNodeWiring.javaJava
public class ManualNodeWiring {    static class Node {        int val;        Node next;
        Node(int val) {            this.val = val;        }
        Node(int val, Node next) {            this.val = val;            this.next = next;        }    }
    public static void main(String[] args) {        Node first = new Node(10);        Node second = new Node(20);        Node third = new Node(30);
        first.next = second;        second.next = third;
        System.out.println("first.val = " + first.val);        System.out.println("first.next.val = " + first.next.val);        System.out.println("first.next.next.val = " + first.next.next.val);        System.out.println("first.next.next.next = " + first.next.next.next);    }}
Output
first.val = 10
first.next.val = 20
first.next.next.val = 30
first.next.next.next = null

What this code does

  • first.next points to second, and first.next.next points to third.
  • Because third.next was never set, it stays null and marks the end of the list.

The three nodes now form the chain 10 -> 20 -> 30 -> null, and first is the only variable the rest of the program needs.

Predict the output

Follow the next links

Read the code and pick what it prints.

Round 1 of 2

Node a = new Node(10);
Node b = new Node(20);
a.next = b;
b.val = 99;
System.out.println(a.next.val);
In Java, a.next = b does not copy object b. Both b and a.next point to the same Node(20) object.

Cost of insert and access, and Java's LinkedList versus your own

Inserting into a linked list is O(1) only when you hold the node before the spot. Without that reference, walking to index i - 1 from head takes O(i) time.

Example 2 · Splicing a New Node in O(1) When You Hold the Predecessor Reference

SpliceInO1Demo.javaJava
public class SpliceInO1Demo {    static class Node {        int val;        Node next;        Node(int val, Node next) {            this.val = val;            this.next = next;        }    }
    static void printChain(Node head) {        StringBuilder sb = new StringBuilder();        for (Node curr = head; curr != null; curr = curr.next) {            sb.append(curr.val).append(" -> ");        }        sb.append("null");        System.out.println(sb);    }
    public static void main(String[] args) {        Node third = new Node(30, null);        Node first = new Node(10, third);        printChain(first);
        // Insert 20 right after 'first' in O(1) pointer updates:        Node inserted = new Node(20, first.next);        first.next = inserted;        printChain(first);
        // Bypass (delete) 20 in O(1) using 'first':        first.next = first.next.next;        printChain(first);    }}
Output
10 -> 30 -> null
10 -> 20 -> 30 -> null
10 -> 30 -> null

What this code does

  • Set inserted.next = first.next before first.next = inserted so you do not lose Node(30).
  • To delete the node after first, first.next = first.next.next skips 20 in O(1) time.

Example 3 · Comparing Cost of get(i) vs addFirst(x): Array vs Linked Nodes

ArrayVsLinkedCostDemo.javaJava
import java.util.LinkedList;
public class ArrayVsLinkedCostDemo {    static class Node {        int val;        Node next;        Node(int val, Node next) { this.val = val; this.next = next; }    }
    static int getAtIndex(Node head, int index) {        Node curr = head;        int steps = 0;        while (curr != null && steps < index) {            curr = curr.next;            steps++;        }        if (curr == null) throw new IndexOutOfBoundsException("Index: " + index);        return curr.val;    }
    public static void main(String[] args) {        Node head = null;        for (int x = 50; x >= 10; x -= 10) {            head = new Node(x, head); // O(1) prepend at head        }        System.out.println("Custom list index 0: " + getAtIndex(head, 0));        System.out.println("Custom list index 3: " + getAtIndex(head, 3));
        LinkedList<Integer> jdkList = new LinkedList<>();        jdkList.addFirst(20);        jdkList.addFirst(10);        jdkList.addLast(30);        System.out.println("java.util.LinkedList: " + jdkList);    }}
Output
Custom list index 0: 10
Custom list index 3: 40
java.util.LinkedList: [10, 20, 30]

What this code does

  • Prepending 5 items with head = new Node(x, head) takes O(1) time per item.
  • getAtIndex(head, 3) walks curr = curr.next 3 times, whereas arr[3] takes 1 step.

Where a linked list is fast:

  • Insert or delete at head: O(1) time with head = new Node(x, head);.
  • Insert or delete after a known node curr: O(1) time with newNode.next = curr.next; curr.next = newNode;.

In Stage 1 you used java.util.LinkedList<E>, which is a doubly linked list. For everyday lists and queues, ArrayList and ArrayDeque are faster because arrays sit together in CPU cache. You build your own Node class when:

  • Solving pointer problems or custom structures: reversing in O(1) space, finding cycles, or building an LRU Cache.

Next step

Check your understanding

10 quick questions