LinkedList in Java

Learn LinkedList end operations and indexed traversal costs, plus when ArrayDeque is a better starting point for Java queues and stacks.

published: reading time: 16 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn LinkedList end operations and indexed traversal costs, plus when ArrayDeque is a better starting point for Java queues and stacks.

LinkedList in Java

LinkedList is a doubly-linked implementation of List and Deque. Each element sits in a node with links to the previous and next nodes. Relinking at a known node or iterator position is constant time, but finding an indexed position takes traversal.

Introduction

LinkedList stores each element in a node with links to its neighbors. Once a node or ListIterator position is known, insertion or removal there takes O(1) relinking. Finding an index first takes O(n) traversal from whichever end is closer. Operations at the head and tail are O(1) because the list keeps references to both ends.

The tradeoff is the node structure: traversal follows links instead of stepping through a backing array, and each node adds allocation and memory overhead. This can make scans less cache-friendly than ArrayList; measure the workload you care about rather than assuming a fixed speed difference. Indexed access is O(n) for LinkedList and O(1) for ArrayList.

For ordinary FIFO or LIFO use, ArrayDeque is usually the simpler starting point. Its API describes it as a resizable-array Deque with amortized constant-time operations and says it is likely faster than LinkedList as a queue. It rejects null; LinkedList remains useful when you need List operations, iterator-positioned edits, or null elements.

When to Use LinkedList

Use LinkedList when:

  • You need List operations and will edit through an already-positioned ListIterator
  • You need a list implementation that permits null elements
  • Your operations are at the head and tail and you also need List behavior

Do not use LinkedList when:

  • You frequently access or insert by index (use ArrayList for indexed access; locating a LinkedList index is O(n))
  • You need a plain queue, stack, or deque without List operations or null support (start with ArrayDeque)
  • You scan through elements in order and have not measured a reason to choose a linked structure
  • You need thread-safe operations
  • Memory is constrained — each node carries two extra pointer fields

Internal Structure

LinkedList uses a static inner Node class with forward and backward pointers:

private static class Node<E> {
    E item;
    Node<E> next;
    Node<E> prev;
}

The list maintains first and last pointers (for O(1) head/tail access) and tracks size.

Mermaid Diagram: LinkedList Node Structure

graph LR
    A["Node prev=null<br/>item=A<br/>next=Node B"] --> B["Node prev=Node A<br/>item=B<br/>next=Node C"]
    B --> C["Node prev=Node B<br/>item=C<br/>next=null"]
    A --> D["null (head)"]
    C --> E["null (tail)"]

Failure Scenarios

Scenario Cause Result
NoSuchElementException Calling getFirst() / pop() on empty list Runtime crash
ConcurrentModificationException Modifying during iteration Runtime crash
Memory overhead Very large lists with many nodes OutOfMemoryError from GC pressure

Trade-Off Table

Aspect LinkedList ArrayList
Random access O(n) — traverses from the nearer end O(1)
Insertion at head O(1) O(n) — shift elements
Insertion at tail O(1) O(1) amortized
Insertion at middle O(n) to reach index, then O(1) to relink O(1) to reach index, then O(n) to shift
Edit at a known iterator position O(1) relinking O(n) shifting
Per-element structure A node with links to both neighbors A reference in a backing array
Storage layout Node links; physical placement is unspecified Reference array; physical placement is unspecified
Iterator invalidation Only on structural changes at that position Only on structural changes at that position

Code Snippets

Deque Operations

The snippets using List.of() require Java 9 or later. The LinkedList and ArrayDeque APIs themselves are available from earlier Java releases.

LinkedList implements Deque, so its addFirst()/addLast(), removeFirst()/removeLast(), and getFirst()/getLast() operations are O(1). They use the list’s head and tail references without traversing nodes.

For an ordinary queue, stack, or deque, start with ArrayDeque unless you need List methods or null elements. It is a resizable-array Deque; most basic operations are amortized O(1), and the Java SE API says it is likely faster than LinkedList when used as a queue. ArrayDeque prohibits null, while LinkedList permits it.

removeFirst() and getFirst() throw NoSuchElementException on an empty list. pollFirst() and pollLast() return null instead. The difference matters: use the throwing variants when an empty list is an error condition; use the poll* variants when an empty list is a valid terminal state, like draining a work queue until it is done. The same pattern applies to peek* versus get* for inspection-only access.

push() and pop() are stack-named aliases for addFirst() and removeFirst(). The explicit end methods make queue and deque code easier to read.

Deque<String> queue = new ArrayDeque<>();
queue.addLast("task1");    // enqueue
queue.addLast("task2");
queue.addFirst("urgent");  // push front
String first = queue.removeFirst();  // "urgent" — amortized O(1)
String next = queue.removeFirst();   // "task1" — amortized O(1)

Indexed and Known-Position Edits

The pointer update is O(1) only after the position is known. listIterator(index) must first walk from the nearer end, so reaching an index takes O(n) in the worst case. Once positioned, ListIterator.add() or remove() relinks nodes in O(1).

List<String> items = new LinkedList<>(List.of("a", "b", "c"));
int position = items.size() / 2;
ListIterator<String> cursor = items.listIterator(position); // O(n) worst case from nearer end
cursor.add("between");                             // O(1) relink at this position

Removing During Iteration

LinkedList iterators are fail-fast: after an unsupported structural modification, they may throw ConcurrentModificationException. This is best-effort bug detection, not a guarantee and not a concurrency mechanism. The exact checks are implementation details; do not rely on a particular method such as hasNext() detecting a change.

When the iterator supports it, it.remove() removes the last returned element while preserving that iterator’s traversal state. it.add(element) inserts at the cursor position; it.set(element) replaces the last returned element without a structural change. These operations follow the ListIterator contract.

The code below filters even numbers by calling it.remove() through the iterator rather than calling nums.remove(element) from outside the loop. Using listIterator() instead of iterator() is important here because ListIterator combines forward traversal with remove() in a single cursor object — exactly what you need for conditional removal during iteration.

LinkedList<Integer> nums = new LinkedList<>(List.of(1, 2, 3, 4, 5));
ListIterator<Integer> it = nums.listIterator();
while (it.hasNext()) {
    if (it.next() % 2 == 0) {
        it.remove();  // Supported by this iterator; keeps traversal valid
    }
}
// nums = [1, 3, 5]

Calling list.remove(element) from outside the iterator changes the list behind the iterator. The iterator may detect that change and throw, but fail-fast behavior is best-effort. If the iterator supports removal and the decision depends on the current element, use it.remove() as shown above.

Converting to Array

toArray() copies LinkedList elements into an array. The method comes in two forms: toArray() returns Object[] (requires casting), while toArray(T[] a) returns a typed array. The typed form is what you want in practice.

LinkedList<String> items = new LinkedList<>(List.of("a", "b", "c"));
String[] array = items.toArray(new String[0]);  // Zero-length array triggers the grow path

The zero-length array pattern is worth understanding. When you pass an array that is too small, toArray() allocates a new array of the correct type and size. This means the returned array is always a freshly allocated one — your original array is never filled in. Passing an empty array avoids wasting space on an array that will be discarded anyway. If you already know the size, passing a pre-sized array is slightly more efficient because it skips the allocation step:

String[] preSized = items.toArray(new String[items.size()]);  // Reuses your array

A few edge cases to keep in mind:

  • Null elements: If the list contains null, it appears as null in the resulting array. The array is not sparse — it has a value at every index.
  • Empty list: toArray(new String[0]) returns a newly allocated zero-length array, not your empty array.
  • Mixed generic types: If the list holds mixed types that do not all extend T, ArrayStoreException is thrown at runtime.

For most cases, items.toArray(new String[0]) is the idiomatic choice.

Observability Checklist

  • Track LinkedList size to detect unbounded growth
  • Monitor iteration time in hot paths — O(n) scans are often misidentified as slow network calls
  • Profile memory usage if it matters — each element has a node object and two links, but the byte cost depends on the JVM, object layout, and configuration
  • Check for repeated list.size() == 0 checks in loops — consider explicit isEmpty() for clarity
  • Monitor GC frequency for large linked lists — nodes are individually garbage-collectable unlike array padding

Security Notes

  • LinkedList is not thread-safe; use ConcurrentLinkedDeque for concurrent access
  • Serializing a LinkedList can be expensive — each node is serialized independently
  • Avoid storing sensitive data in nodes that may persist in memory after the list is cleared; unlike arrays, there is no efficient way to zero out node contents

Common Pitfalls / Anti-Patterns

  1. Assuming O(1) indexed insertion: Relinking is O(1) when you already have the node or an iterator at the position. Finding an index with listIterator(index) takes O(n) traversal from the nearer end.
  2. Memory overhead: A LinkedList of 1 million Integer objects requires ~48MB (3 pointers + object header per node) vs ~4MB for an ArrayList of the same elements.
  3. Reverse iteration: Use list descendingIterator() for efficient tail-to-head traversal
  4. pollFirst() vs removeFirst(): pollFirst() returns null on empty list; removeFirst() throws NoSuchElementException
  5. addFirst() vs push(): Both insert at the head; push() is the stack-named alias for addFirst().

Quick Recap

  • LinkedList has O(1) operations at the head and tail; edits at an already-known node or iterator position are also O(1)
  • Reaching an index with listIterator(index) takes O(n) traversal from the nearer end
  • Random access is O(n) — do not use LinkedList when index-based access is frequent
  • Implements both List and Deque; for ordinary queue or stack use, start with ArrayDeque unless you need List methods or null elements
  • Each node stores two pointers in addition to the value — higher memory overhead than ArrayList
  • Linked traversal may have worse locality than an array-backed list; measure sequential scans for your workload

Interview Questions

1. What is the time complexity of inserting an element at the middle of a LinkedList?
Finding an indexed position takes O(n) traversal from the nearer end; once a node or `ListIterator` position is known, relinking takes O(1). `ArrayList` reaches an index in O(1) but shifts elements for a middle insertion, so that operation is O(n).
2. Why is LinkedList generally slower than ArrayList for sequential iteration?
`LinkedList` follows node references, while `ArrayList` traverses a backing array. The layouts can affect cache behavior, but the size of the difference depends on the JDK, hardware, and workload. Measure the sequential traversal you care about rather than assuming a fixed speed ratio.
3. How does LinkedList implement the Deque interface?
`LinkedList` supports `Deque` operations at both ends in O(1), including `addFirst()`, `addLast()`, `removeFirst()`, and `removeLast()`. The same `Deque` methods work with `ArrayDeque`, which is usually the starting choice for a queue unless you need `List` behavior or `null` elements.
4. What happens when you call `removeFirst()` on an empty LinkedList?
`NoSuchElementException` is thrown. Use `pollFirst()` instead if you want `null` returned on an empty list rather than an exception. This distinction is important when processing input that may be empty."

5. How much extra memory does each LinkedList node consume compared to an ArrayList element?
There is no portable bytes-per-node estimate: object headers, reference widths, alignment, and layout depend on the JVM and its configuration. A `LinkedList` adds node objects and links, while an `ArrayList` keeps element references in a backing array. Measure the actual memory footprint on the target runtime if it matters.

6. What is the difference between `pollFirst()` and `removeFirst()`?
Both remove and return the first element. However, `pollFirst()` returns `null` when the list is empty, while `removeFirst()` throws `NoSuchElementException`. Similarly, `peekFirst()` returns `null` on empty, and `getFirst()` throws. Use `poll*` when empty is a valid/expected state."

7. Why is LinkedList's iterator not fail-safe when structural changes happen via another iterator?
LinkedList iterators are fail-fast: they may throw `ConcurrentModificationException` after an unsupported structural change. Detection is best-effort, so it is not a thread-safety guarantee. Changes made through the iterator's supported `remove()` or `add()` methods follow that iterator's contract.

8. How does descendingIterator() work in LinkedList?
`descendingIterator()` returns an iterator starting at the last node and moving backward using `previous()`. It is implemented as a `ListIterator` wrapped around `listIterator(size())` — essentially positioning the cursor at the end and iterating in reverse."

9. When does LinkedList convert to a tree structure?
Unlike HashMap, LinkedList does **not** convert to a tree structure for large sizes. It remains a doubly-linked list regardless of size. Each node is always a `Node` with prev/next pointers. If you need O(log n) operations on ordered data, use `TreeSet` or `TreeMap` instead."

10. What is the time complexity of checking if a LinkedList contains a specific element?
**O(n)** — linear search. LinkedList has no index-based lookup optimization for arbitrary access. Every `contains()` call traverses from the head (or tail if the element is likely near the end) until the element is found or the list ends."

11. How does LinkedList implement the Queue interface's FIFO operations?
`LinkedList` implements `Queue` with `offer()` at the tail and `poll()` or `peek()` at the head. Its `Deque` methods add and remove at either end in O(1). `ArrayDeque` supports the same queue operations with amortized O(1) basic costs and is usually the starting choice unless you need `List` behavior or `null` elements.
12. What is the difference between `remove()` and `poll()` in LinkedList?
Both remove and return the first element. `remove()` throws `NoSuchElementException` when the list is empty. `poll()` returns `null` when empty. Similarly, `getFirst()` throws on empty, while `peekFirst()` returns `null`. Use `poll`/`peek` when empty is a valid expected state."

13. How does LinkedList perform in a tail-add-heavy workload?
`LinkedList.addLast()` is O(1), but it creates a node for each element. `ArrayDeque` provides amortized O(1) end operations and is likely faster than `LinkedList` as a queue according to the Java SE API. It rejects `null` elements.
14. How does `listIterator(index)` work in LinkedList?
`listIterator(index)` returns a `ListIterator` at the requested index, walking from whichever end is closer. Reaching that position is O(n) in the worst case. Afterward, insertion or removal through the iterator relinks nodes in O(1).
15. What is the difference between LinkedList and ArrayDeque for queue operations?
Both support operations at the front and back. `LinkedList` allocates a node per element and also implements `List`; `ArrayDeque` is an array-backed `Deque` with amortized O(1) basic operations and does not permit `null`. The Java SE API says `ArrayDeque` is likely faster than `LinkedList` when used as a queue.
16. Can LinkedList's node structure be garbage collected when elements are removed?
Yes, when you remove an element from LinkedList, the node becomes eligible for garbage collection once no references to it exist. Unlike arrays where removal leaves gaps, LinkedList nodes are individually reclaimed by the GC. However, the node's element (if mutable and referenced elsewhere) may still be alive."

17. How does LinkedList handle very large lists in terms of memory allocation?
There is no portable bytes-per-node estimate: object headers, reference sizes, alignment, and layout depend on the JVM and configuration. A linked list stores node links, while an array list stores references in an array; physical placement and cache behavior are implementation- and workload-dependent. Measure memory and traversal on the target runtime if they matter.

18. What is the difference between `peekFirst()` and `getFirst()` in LinkedList?
`peekFirst()` returns `null` if the list is empty; `getFirst()` throws `NoSuchElementException`. Similarly, `peek()` and `element()` have the same distinction for Queue. Use `peek*` when empty is a valid expected state; use `get*` when empty indicates an error condition."

19. How does LinkedList's `addAll()` method work efficiency-wise?
`addAll()` with an index inserts elements at that position, requiring traversal to find the position (O(n)) plus node allocation for each element. Without an index, `addAll()` appends at the tail in O(1) amortized per element. Each element requires a new node allocation and pointer updates."

20. What is the difference between using LinkedList as a Stack versus ArrayDeque for stack operations?
Both implement stack operations with `push()`, `pop()`, and `peek()`. `ArrayDeque` is the usual starting point for a stack when you do not need `List` methods or `null` elements. It uses a resizable array and amortized O(1) basic operations; `LinkedList` adds a node for each element and also supports `List` operations.

Further Reading

Conclusion

LinkedList has O(1) operations at the head and tail. Insertion or removal is also O(1) once the node or ListIterator position is known; finding an indexed position takes O(n) traversal from the nearer end. This is why indexed insertion is not automatically constant time.

For List workloads, choose based on access pattern: ArrayList suits frequent indexed access, while LinkedList can fit when edits happen through an already-positioned iterator or when the list must permit null. For ordinary FIFO or LIFO behavior, ArrayDeque is the usual starting point. Its basic operations are amortized O(1), it prohibits null, and the Java SE API says it is likely faster than LinkedList as a queue.

See Queue and Deque for the queue interfaces and TreeSet for ordered unique collections.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals