LinkedList and when to use it
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · Building nodes by hand
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); }}Mumbai -> Pune -> Bengaluru Mumbai -> Pune -> Satara -> Bengaluru
What this code does
- Each
Nodeholds a value and a reference to the next node;nullmarks the end. Walking the chain meanscurrent = current.nextuntilnull. - Inserting Satara changes just two links. No other node moves, unlike an array where later items must shift.
- Java's
LinkedListuses the same idea with aprevlink 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
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()); }}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
addFirstputs the engine in front of S1 without moving anything;addLasthooks a coach to the end.removeLastreturns the item it removed, so the guard van can be put back after A1.get(2)also works, becauseLinkedListis aList, but it walks from the front to find index 2.
Example 3 · Crash: getFirst on an empty list
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()); }}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 throwsNoSuchElementException. - Note the different exception from
ArrayList.get(0), which throwsIndexOutOfBoundsException.
Example 4 · Safe ends and removing while walking
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); }}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()returnsnullon an empty list instead of throwing, and anisEmpty()check protectsgetFirst().it.remove()unlinks the node the iterator is standing on: O(1), no shifting, noConcurrentModificationException.- A
ListIterator(fromlistIterator()) can alsoaddright 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.
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
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); }}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 takesisteps, 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
LinkedListstarts 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.
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 needOn 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 memoryArrayList: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