LinkedList in Java

Learn how Java's LinkedList works as a doubly-linked list, its time complexities, Deque capabilities, and when to prefer it over ArrayList.

LinkedList<E> is a doubly-linked list implementation that implements both the List and Deque interfaces. Each element is stored in a separate Node object that holds the element value plus references to the previous and next nodes. This structure makes adding and removing elements at either end O(1), but random access by index requires traversing the list from the nearest end, making it O(n). LinkedList is one of the few Java collection classes that implements two major interfaces, giving it queue and stack behaviour in addition to list behaviour.

Internal Structure

Each node in a LinkedList is an instance of the inner class Node<E>:

Node { E item; Node<E> next; Node<E> prev; }

The LinkedList object itself holds references to the first and last nodes, plus a size field. Operations at the head or tail are O(1) because no traversal is needed. Operations that require finding an element by index first check whether the index is closer to the head or tail, then traverse from that end.

Time Complexities

Operation Complexity Notes
get(i) O(n) Traverses from head or tail
set(i, e) O(n) Must find node first
add(e) (at end) O(1) Links new node to tail
addFirst(e) / addLast(e) O(1) Links to head or tail
add(i, e) (at index) O(n) Must traverse to index
remove() / removeFirst() / removeLast() O(1) Unlinks head or tail
remove(i) (at index) O(n) Must traverse to index
contains(o) O(n) Linear scan
size() O(1) Field read

Example 1: LinkedList as a List and Deque

import java.util.LinkedList;
import java.util.List;

public class LinkedListBasics {
    public static void main(String[] args) {
        LinkedList<String> tasks = new LinkedList<>();

        // List operations
        tasks.add("Task A");
        tasks.add("Task B");
        tasks.add("Task C");
        System.out.println(tasks); // [Task A, Task B, Task C]

        // Deque operations — add/remove at both ends in O(1)
        tasks.addFirst("URGENT");
        tasks.addLast("LOW");
        System.out.println(tasks); // [URGENT, Task A, Task B, Task C, LOW]

        System.out.println("First: " + tasks.peekFirst()); // URGENT
        System.out.println("Last:  " + tasks.peekLast());  // LOW

        tasks.pollFirst(); // removes URGENT
        tasks.pollLast();  // removes LOW
        System.out.println(tasks); // [Task A, Task B, Task C]

        // Index-based access (O(n))
        System.out.println(tasks.get(1)); // Task B
    }
}

Example 2: Using LinkedList as a Queue and Stack

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class LinkedListQueueStack {
    public static void main(String[] args) {
        // As a FIFO Queue
        Queue<String> queue = new LinkedList<>();
        queue.offer("first");
        queue.offer("second");
        queue.offer("third");
        System.out.println(queue.poll()); // first (FIFO)
        System.out.println(queue.peek()); // second

        // As a Stack (Deque interface)
        Deque<String> stack = new LinkedList<>();
        stack.push("bottom");
        stack.push("middle");
        stack.push("top");
        System.out.println(stack.pop()); // top (LIFO)
        System.out.println(stack.peek()); // middle

        // NOTE: ArrayDeque is preferred over LinkedList for both Queue and Stack
        // because it has lower memory overhead and better cache performance.
        Deque<String> betterStack = new ArrayDeque<>();
        betterStack.push("a");
        betterStack.push("b");
        System.out.println(betterStack.pop()); // b
    }
}

LinkedList vs. ArrayList

Feature LinkedList ArrayList
Backing structure Doubly-linked nodes Resizable array
get(i) O(n) O(1)
add at end O(1) Amortized O(1)
add/remove at ends O(1) O(n)
add/remove at index O(n) O(n)
Memory per element ~48 bytes (object + two refs) ~4–8 bytes (array slot)
Cache performance Poor (pointer chasing) Good (contiguous memory)
Also implements List, Deque, Queue List, RandomAccess

Despite LinkedList's theoretical advantage for head/tail operations, ArrayList or ArrayDeque are usually faster in practice for most real workloads due to better CPU cache utilisation.

Common Mistakes

  • Using LinkedList for random access. Calling get(i) in a loop over a LinkedList is O(n²). Use an ArrayList whenever you need index-based access.
  • Preferring LinkedList over ArrayDeque for stacks/queues. ArrayDeque has the same O(1) end-access performance without the per-node object overhead. The Java documentation itself recommends ArrayDeque over LinkedList for queue/stack use cases.
  • Iterating with index-based for instead of for-each. A for (int i = 0; i < list.size(); i++) { list.get(i); } loop on a LinkedList is O(n²) because each get(i) restarts traversal. Use for-each (which uses the iterator) to get O(n) total traversal.
  • Forgetting LinkedList allows null. LinkedList permits null elements, unlike ArrayDeque. This can cause NullPointerException confusion when switching implementations.
  • Holding the concrete type. Declaring LinkedList<E> instead of List<E> or Deque<E> exposes the implementation and makes it harder to swap to ArrayList or ArrayDeque later.

Best Practices

  • Use LinkedList only when you specifically need O(1) insertions/removals at both ends AND do not need random access — for example, as a Deque for undo/redo or a sliding-window buffer.
  • Prefer ArrayDeque over LinkedList for pure queue or stack usage.
  • Declare variables as List<E> or Deque<E>, not LinkedList<E>, to preserve flexibility.
  • When iterating a LinkedList, always use the enhanced for loop or an explicit iterator — never index-based access.
  • Profile before choosing LinkedList over ArrayList; the pointer-chasing overhead of linked nodes frequently makes it slower even for middle insertions on modern hardware.

Interview Questions

1. How is LinkedList implemented internally?

LinkedList uses a doubly-linked list of Node<E> objects, each containing the element and next/prev references. The class holds references to the first and last nodes and a size counter. Operations at the head or tail are O(1); operations by index require traversal from the nearest end, making them O(n).

2. When would you choose LinkedList over ArrayList?

Choose LinkedList when you need frequent O(1) insertions and removals at both ends of the collection without random access — for example, as a deque, a job queue, or an undo buffer. For most other purposes, including random access, sorted iteration, or bulk appends, ArrayList is faster.

3. What interfaces does LinkedList implement?

LinkedList implements List<E>, Deque<E>, Queue<E>, and Cloneable, Serializable. The Deque implementation means it supports push/pop, offer/poll/peek for both ends, and full double-ended queue semantics.

4. Why is ArrayDeque preferred over LinkedList for queue/stack use?

ArrayDeque stores elements in a circular resizable array, which has better CPU cache performance than the pointer-chasing required by LinkedList nodes. ArrayDeque also uses less memory per element since it does not allocate a Node wrapper for each element. The Java ArrayDeque documentation explicitly recommends it over LinkedList for LIFO stacks and FIFO queues.

5. What happens when you call get(index) on a LinkedList?

The implementation checks whether index is in the first or second half of the list, then traverses forward from the head or backward from the tail until it reaches the target node. This makes get(i) O(n/2) = O(n) in the worst case.

6. Is LinkedList thread-safe?

No. Like most JCF collections, LinkedList is not synchronised. Concurrent modification from multiple threads can corrupt internal state. For thread-safe deque behaviour, use ConcurrentLinkedDeque or LinkedBlockingDeque from java.util.concurrent.

7. Can LinkedList contain null elements?

Yes. LinkedList permits null elements, including multiple null values. This distinguishes it from ArrayDeque, PriorityQueue, and TreeSet, which throw NullPointerException when you try to add null.

Summary

  • LinkedList is a doubly-linked list implementing both List and Deque.
  • O(1) add/remove at either end; O(n) for index-based access and middle insertions.
  • Higher memory overhead per element compared to ArrayList due to node objects.
  • ArrayDeque is the preferred alternative for pure queue and stack use because of better cache performance.
  • Always iterate with for-each, never with an index-based loop, to avoid O(n²) behaviour.

Continue Learning

Previous: ArrayList | Next: Vector

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.