skip to content

Why is std::collections::LinkedList rarely the right choice in Rust, even for a queue that removes items from the middle?

level: middleimportance: should knowfreq 40%

answer

  1. std's own note
  2. one allocation per node
  3. no stable cursor
  4. append is the exception

basics

~20 s

LinkedList allocates a node per element and walks scattered memory, and std's docs say Vec or VecDeque is almost always better. On stable Rust its cursor and remove-at methods are unstable, so middle removal walks the list anyway.

solid answer

~40 s

Each `LinkedList` element is a separate heap node with `next` and `prev` pointers, so pushes allocate, iteration chases pointers, and the cache helps little; std's own docs note that `Vec` or `VecDeque` is almost always better. The textbook win, O(1) insert or remove at a held position, needs cursors, and in Rust 1.99 `cursor_front_mut`, `remove(at)` and `retain` are unstable, failing with E0658 on stable. So removing from the middle means walking: `extract_if` (stable since 1.87) is O(n), the same order as `VecDeque::retain` on a faster structure. What remains real is O(1) `append` of two lists and no reallocation spikes. For a queue use `VecDeque`; for stable handles use a `Vec` of slots addressed by index.

code

rust · 19 lines
rust
use std::collections::{LinkedList, VecDeque};

fn main() {
    // Remove every even id from the middle of each container.
    let mut list: LinkedList<u32> = (1..=8).collect();
    let evens: LinkedList<u32> = list.extract_if(|id| *id % 2 == 0).collect();

    let mut deque: VecDeque<u32> = (1..=8).collect();
    deque.retain(|id| *id % 2 != 0);

    println!("list  {:?} removed {:?}", list, evens);
    println!("deque {:?}", deque);

    // O(1) splice of two lists — LinkedList's one real advantage.
    let mut a: LinkedList<u32> = LinkedList::from([1, 2]);
    let mut b: LinkedList<u32> = LinkedList::from([3, 4]);
    a.append(&mut b);
    println!("appended {:?}, b now empty: {}", a, b.is_empty());
}

go deeper

for a junior

Know that std has a LinkedList but that its own docs steer you to Vec or VecDeque instead.

for a middle

Explain the per-node allocation and cache cost, and that removing from the middle on stable means an O(n) walk with extract_if.

for a senior

Name the unstable cursor, remove and retain features (E0658 on stable), and the real remaining uses: O(1) append and no reallocation spikes.

for a principal

When a design calls for pointer-linked structures, steer toward index-based slots so ownership stays simple and data stays contiguous.

## What std itself says `std::collections::LinkedList<T>` is a **doubly linked list with owned nodes**. It supports pushing and popping at either end in constant time. Its own documentation then adds a note: it is **almost always better to use `Vec` or `VecDeque`**, because array-based containers are generally faster, more memory efficient, and make better use of the CPU cache. An interviewer asking this question wants to hear why that note is right **in Rust specifically**, not just in general. ## Cost per element Each element lives in its own heap-allocated `Node` holding `next`, `prev` and the element. So compared with a `VecDeque`: - every push is a **separate allocation**, and every pop a separate free; - each element carries **two pointers** of overhead; - iteration follows pointers to scattered addresses, so the CPU cache and prefetcher help far less than with one contiguous buffer. ## The textbook advantage is not reachable on stable Rust A linked list earns its keep when you hold a position and insert or remove there in O(1). In Rust 1.99 the API that would let you do that is **unstable**: | Method | Status in Rust 1.99 | |---|---| | `cursor_front`, `cursor_front_mut` and the `Cursor` types | unstable, feature `linked_list_cursors` | | `remove(at)` | unstable, feature `linked_list_remove` | | `retain` | unstable, feature `linked_list_retain` | | `extract_if` | stable since Rust 1.87 | | `append` | stable, documented O(1) | | `split_off(at)` | stable, walks to the index | Calling an unstable method on the stable compiler fails with **E0658**, "use of unstable library feature `linked_list_cursors`". Without cursors you cannot keep a handle to a node, and the borrow checker would not let you hold a reference into the list while also mutating it. So "remove from the middle" on stable means walking: `extract_if` (since 1.87) visits every node and unlinks the ones its predicate selects, which is O(n) — the same order as `VecDeque::retain`, on a slower structure. ## What `LinkedList` still does well Two properties are genuine: 1. **`append` is O(1)**: it relinks another list's nodes onto the end, leaving the other list empty. Concatenating large queues repeatedly is the one workload where it beats an array. 2. **No reallocation spikes**: a push never copies existing elements, because each node is separate. An occasional O(n) grow in a `VecDeque` is gone — but every push now pays an allocator call. Elements also never move in memory, though safe code rarely benefits, since it cannot hold references into the list while mutating it. ## What to use instead - A **queue or deque**: `VecDeque`, with `retain` for removals from the middle. - **Order does not matter**: `Vec::swap_remove`, O(1). - **Stable handles to items** that are removed out of order: a `Vec` of slots addressed by index, with a free list, so the "pointer" is a `usize` the borrow checker does not track. - **Ordered by key**: a `BTreeMap`, which also removes by key in logarithmic time. ## Measuring rather than guessing If someone insists a list is faster for their workload, a benchmark settles it quickly: fill both containers with the same data, run the real mix of pushes, pops and middle removals, and compare. On typical workloads the array-based container wins because of allocation count and memory locality, which is the reason std's own note gives. Two things are worth checking in such a review: 1. Whether the "middle removal" is really by position, or by predicate, which `retain` handles in one pass. 2. Whether the order actually matters, since `swap_remove` turns a removal into O(1) when it does not. ## How to answer in an interview A strong answer ties the three facts together: the per-node allocation and cache cost, the **unstable cursor API** that hides the one O(1) operation linked lists are known for, and the **two real uses** that remain, `append` and steady push latency. Building a list by hand with `Box` or raw pointers is a separate subject, covered with `Box` and with unsafe code.

  • What is the one LinkedList operation an array-based container cannot match?
    `append`, documented as O(1) time and memory: it relinks the other list's nodes onto the end and leaves the other list empty. `VecDeque::append` must move the other deque's elements into its buffer, which is O(n) in the appended length. If you concatenate long queues repeatedly, that difference can matter.
  • If you need handles to items that are removed out of order, what do you use instead of a linked list?
    A `Vec` of slots addressed by index, with a free list for reuse: the handle is a `usize`, removal marks the slot free in O(1), and the data stays contiguous. Because the handle is not a reference, the borrow checker does not stop you mutating the container while handles are held.

  • LinkedList gives O(1) removal from the middle on stable Rust.
  • LinkedList uses less memory than VecDeque because it never over-allocates.
  • LinkedList::remove(at) is a stable method.
  • Iterating a LinkedList is as cache-friendly as iterating a Vec.
  • Rust has no linked list in std, so you must write one yourself.

Assumes Rust 1.99; LinkedList cursors, remove and retain are unstable there, and LinkedList::extract_if is stable since Rust 1.87.