Skip to lesson

LinkedList and when to use it

A LinkedList stores each item in its own small object, called a node, and links the nodes together like the coaches of a train. Adding or removing at either end is cheap, but reaching the item at an index means walking along the chain.

Nodes and links

A LinkedList stores each item in its own small object called a node. A node holds one item plus two links, one to the next node and one to the previous node, so the nodes form a chain that you walk one link at a time.

A node holds one item and two references: one to the next node and one to the previous node. Because the links go both ways, Java's LinkedList is a doubly linked list. The list remembers the first node, the last node and the size.

A LinkedList is a chain of nodes holding Pen, Cup and Bag. Each node has a next link and a prev link; the list remembers the first and last node, and the end links are null. To reach index 2, start at first and follow next twice.

Example 1 · Building nodes by hand

StationChainDemo.javaJava
class Node {    String value;    Node next;
    Node(String value) {        this.value = value;    }}
public class StationChainDemo {    static void printRoute(Node first) {        StringBuilder route = new StringBuilder();        Node current = first;        while (current != null) {            route.append(current.value);            if (current.next != null) {                route.append(" -> ");            }            current = current.next;        }        System.out.println(route);    }
    public static void main(String[] args) {        Node mumbai = new Node("Mumbai");        Node pune = new Node("Pune");        Node bengaluru = new Node("Bengaluru");        mumbai.next = pune;        pune.next = bengaluru;        printRoute(mumbai);
        Node satara = new Node("Satara");        satara.next = pune.next;        pune.next = satara;        printRoute(mumbai);    }}
Output
Mumbai -> Pune -> Bengaluru
Mumbai -> Pune -> Satara -> Bengaluru

What this code does

  • Each Node holds a value and a reference to the next node; null marks the end. Walking the chain means current = current.next until null.
  • Inserting Satara changes just two links. No other node moves, unlike an array where later items must shift.
  • Java's LinkedList uses the same idea with a prev link too, so it can walk in both directions.

There is no backing array. Nothing ever grows or gets copied, and inserting never shifts other items: only a few links change.

The price is that the nodes are scattered in memory. The only way to reach the 500th node is to start at one end and follow the links.

Working at both ends

LinkedList has extra methods for the two ends: addFirst, addLast, getFirst, getLast, removeFirst and removeLast. Each one touches only the first or last node, so each is O(1).

Example 2 · A train at both ends

TrainCoachesDemo.javaJava
import java.util.LinkedList;
public class TrainCoachesDemo {    public static void main(String[] args) {        LinkedList<String> train = new LinkedList<>();        train.addLast("S1");        train.addLast("S2");        train.addLast("B1");        train.addFirst("Engine");        train.addLast("Guard");        System.out.println("Train: " + train);        System.out.println("Front: " + train.getFirst() + ", back: " + train.getLast());
        String detached = train.removeLast();        train.addLast("A1");        train.addLast(detached);        System.out.println("Moved " + detached + " behind A1: " + train);
        System.out.println("Coach at index 2: " + train.get(2));        System.out.println("Coaches: " + train.size());    }}
Output
Train: [Engine, S1, S2, B1, Guard]
Front: Engine, back: Guard
Moved Guard behind A1: [Engine, S1, S2, B1, A1, Guard]
Coach at index 2: S2
Coaches: 6

What this code does

  • addFirst puts the engine in front of S1 without moving anything; addLast hooks a coach to the end.
  • removeLast returns the item it removed, so the guard van can be put back after A1.
  • get(2) also works, because LinkedList is a List, but it walks from the front to find index 2.

Example 3 · Crash: getFirst on an empty list

EmptyQueueCrashDemo.javaJava
import java.util.LinkedList;
public class EmptyQueueCrashDemo {    public static void main(String[] args) {        LinkedList<String> tokens = new LinkedList<>();        tokens.addLast("Token 1");        tokens.removeFirst();
        System.out.println("Tokens left: " + tokens.size());        System.out.println("Next: " + tokens.getFirst());    }}
Sample output
Tokens left: 0
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.LinkedList.getFirst(LinkedList.java:248)
	at EmptyQueueCrashDemo.main(EmptyQueueCrashDemo.java:10)

What this code does

  • The only token was removed, so the list is empty. getFirst() has no node to return and throws NoSuchElementException.
  • Note the different exception from ArrayList.get(0), which throws IndexOutOfBoundsException.

Example 4 · Safe ends and removing while walking

PlaylistDemo.javaJava
import java.util.Iterator;import java.util.LinkedList;import java.util.ListIterator;
public class PlaylistDemo {    public static void main(String[] args) {        LinkedList<String> queue = new LinkedList<>();        System.out.println("Next song: " + queue.peekFirst());        if (!queue.isEmpty()) {            System.out.println("Playing " + queue.getFirst());        }
        LinkedList<String> playlist = new LinkedList<>();        playlist.addLast("Morning Focus");        playlist.addLast("Ad");        playlist.addLast("Deep Work");        playlist.addLast("Ad");        playlist.addLast("Evening Calm");
        Iterator<String> it = playlist.iterator();        while (it.hasNext()) {            if (it.next().equals("Ad")) {                it.remove();            }        }        System.out.println("Without ads: " + playlist);
        ListIterator<String> walker = playlist.listIterator();        while (walker.hasNext()) {            if (walker.next().equals("Deep Work")) {                walker.add("Night Study");            }        }        System.out.println("After insert: " + playlist);    }}
Output
Next song: null
Without ads: [Morning Focus, Deep Work, Evening Calm]
After insert: [Morning Focus, Deep Work, Night Study, Evening Calm]

What this code does

  • peekFirst() returns null on an empty list instead of throwing, and an isEmpty() check protects getFirst().
  • it.remove() unlinks the node the iterator is standing on: O(1), no shifting, no ConcurrentModificationException.
  • A ListIterator (from listIterator()) can also add right after the current item. This is where a linked list really is O(1) in the middle.

These methods are not in the List interface (in Java 17), so declare the variable as LinkedList<String> to call them. LinkedList also implements List, so add, get, set, remove and for-each all work as with ArrayList.

On an empty list, getFirst() and removeFirst() throw NoSuchElementException. peekFirst() and pollFirst() return null instead. The Queues module uses these methods through the Deque interface.

Predict the output

Both ends of a LinkedList

Read each snippet and pick what it prints.

Round 1 of 4

Items go in at both ends.

LinkedList<String> parcels = new LinkedList<>();
parcels.addLast("A");
parcels.addFirst("B");
parcels.addLast("C");
System.out.println(parcels);

get(i) has to walk

To find index i, a LinkedList starts at the nearer end and follows links one by one. For an item in the middle of a 1 lakh list, that is about 50,000 steps, so get(i) and set(i, x) are O(n).

Example 5 · Counting steps: get(i) walks the chain

WalkCostDemo.javaJava
class MiniLinkedList {    private static class Node {        int value;        Node next;
        Node(int value) {            this.value = value;        }    }
    private Node first;    private Node last;    private int size;    long steps = 0;
    void addLast(int value) {        Node node = new Node(value);        if (first == null) {            first = node;        } else {            last.next = node;        }        last = node;        size++;    }
    int size() {        return size;    }
    int get(int index) {        Node current = first;        for (int i = 0; i < index; i++) {            current = current.next;            steps++;        }        return current.value;    }
    long sumByWalking() {        long sum = 0;        Node current = first;        while (current != null) {            sum = sum + current.value;            current = current.next;            steps++;        }        return sum;    }}
public class WalkCostDemo {    public static void main(String[] args) {        MiniLinkedList list = new MiniLinkedList();        for (int i = 1; i <= 1000; i++) {            list.addLast(i);        }
        long sum = 0;        for (int i = 0; i < list.size(); i++) {            sum = sum + list.get(i);        }        System.out.println("Index loop: sum " + sum + ", steps " + list.steps);
        list.steps = 0;        System.out.println("One walk:   sum " + list.sumByWalking() + ", steps " + list.steps);    }}
Output
Index loop: sum 500500, steps 499500
One walk:   sum 500500, steps 1000

What this code does

  • Each get(i) starts at the first node and takes i steps, so the index loop costs 0 + 1 + ... + 999 = 499,500 steps.
  • Walking the chain once, as for-each does, costs one step per node: 1,000 steps for the same sum.
  • The real LinkedList starts from whichever end is nearer, which halves the walk, but an index loop is still O(n²).

This makes an index loop for (int i = 0; i < list.size(); i++) list.get(i) a trap: each get walks again from the end, so the loop is O(n²). A for-each loop or an Iterator walks the chain once: O(n).

Inserting "in the middle is O(1)" is only half true. Changing the links is O(1), but finding the spot is O(n), unless an iterator is already standing there.

ArrayList is usually the better choice

ArrayList is usually the better choice for a list, and ArrayDeque for a queue or stack. Each node is a separate object, so a LinkedList uses more memory and is slower to read.

Java
List<Integer> marks = new ArrayList<>();       // the default listDeque<String> waiting = new ArrayDeque<>();    // queue or stack: work at the endsList<String> coaches = new LinkedList<>();     // only for a measured need

On a typical 64-bit JVM a node costs about 24 bytes, while an ArrayList slot costs about 4. Array items also sit next to each other in memory, which the processor reads very quickly. In real measurements, ArrayList wins most everyday jobs, even many inserts in the middle of small and medium lists.

For a queue or a stack (work at the ends only), ArrayDeque is faster than LinkedList. The Queues, Stacks & Priority Queues module teaches it. So start with ArrayList. Choose LinkedList only when you need a List and you really add and remove at the ends or through an iterator most of the time, and better still, measure.

  • LinkedList: ends O(1), get(i) O(n), more memory
  • ArrayList: get(i) O(1), add at end O(1) amortized, front O(n)
  • Reading by index or looping → ArrayList
  • Queue or stack → ArrayDeque (Queues module)

Next step

Check your understanding

12 quick questions